Files
sam-api/app/Services/RegisterService.php
hskwon fdef567863 feat: 로그인 API에 roles 정보 추가
- MemberService::getUserInfoForLogin(): 사용자 역할 조회 로직 추가
- ApiController::login(): 응답에 roles 포함
- AuthApi (Swagger): roles 응답 스키마 추가
- 로그인 시 해당 회원의 역할 목록 반환 (id, name, description)

fix: 회원가입 시 UserTenant 생성 누락으로 인한 로그인 실패 수정

근본 원인:
- RegisterService는 TenantUserProfile만 생성
- MemberService::getUserInfoForLogin()은 UserTenant 조회
- 회원가입 직후 로그인 시 테넌트 조회 실패 (userTenants->isEmpty() = true)

해결 방안:
- RegisterService에 UserTenant::create() 추가
- TenantUserProfile: 프로필 정보 (부서, 직급 등)
- UserTenant: 접근 권한 관리 (is_active, is_default, joined_at)

영향도:
- 신규 사용자: 로그인 가능하게 수정
- 기존 사용자: 영향 없음 (user_tenants 데이터 이미 존재)

fix: 로그인 시 테넌트 없는 경우 roles 누락 오류 수정

- MemberService::getUserInfoForLogin(): 테넌트가 없는 경우에도 roles 빈 배열 반환
- Undefined array key 'roles' 에러 해결

MemberService.php 권한 조회 로직 수정 - 역할 기반 권한 지원

[문제]
- 회원가입 후 로그인 시 메뉴 리스트가 표시되지 않음
- RegisterService에서 역할에 권한 할당(role_has_permissions)하고
  사용자에게 역할 부여(model_has_roles)
- 하지만 MemberService는 model_has_permissions(직접 사용자 권한)만 조회

[원인]
- Spatie Permission 아키텍처 불일치
- 권한이 역할에 저장되었으나 직접 사용자 권한 테이블만 조회

[해결]
- model_has_roles → role_has_permissions → permissions 조인 쿼리로 변경
- UNION으로 직접 권한(model_has_permissions)도 지원하는 하이브리드 방식
- 역할 기반 권한과 직접 권한 모두 조회 가능

[변경 파일]
- app/Services/MemberService.php (getUserInfoForLogin 메서드, 239-259줄)
2025-11-11 10:56:39 +09:00

155 lines
5.9 KiB
PHP

<?php
namespace App\Services;
use App\Helpers\TenantCodeGenerator;
use App\Models\Commons\Menu;
use App\Models\Members\User;
use App\Models\Members\UserTenant;
use App\Models\Tenants\Tenant;
use App\Models\Tenants\TenantUserProfile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;
class RegisterService
{
/**
* 회원가입 처리 (테넌트 생성 + 사용자 생성 + 시스템 관리자 역할 부여)
*
* @param array $params [
* 'user_id' => string,
* 'name' => string,
* 'email' => string,
* 'phone' => string,
* 'password' => string,
* 'position' => string (optional),
* 'company_name' => string,
* 'business_num' => string (optional),
* 'company_scale' => string (optional),
* 'industry' => string (optional),
* ]
* @return array ['user' => array, 'tenant' => array, 'menus' => array, 'roles' => array]
*/
public static function register(array $params): array
{
return DB::transaction(function () use ($params) {
// 1. Generate unique tenant code from company name
$code = TenantCodeGenerator::generate($params['company_name']);
// 2. Create Tenant with trial status and options
$tenant = Tenant::create([
'company_name' => $params['company_name'],
'code' => $code,
'business_num' => $params['business_num'] ?? null,
'tenant_st_code' => 'trial', // 트라이얼 상태
'options' => [
'company_scale' => $params['company_scale'] ?? null,
'industry' => $params['industry'] ?? null,
],
]);
// 3. Create default menus for tenant
$menuIds = MenuBootstrapService::createDefaultMenus($tenant->id);
// 4. Create User with hashed password and options
$user = User::create([
'user_id' => $params['user_id'],
'name' => $params['name'],
'email' => $params['email'],
'phone' => $params['phone'] ?? null,
'password' => Hash::make($params['password']),
'options' => [
'position' => $params['position'] ?? null,
],
]);
// 5. Create TenantUserProfile (tenant-user profile mapping)
TenantUserProfile::create([
'user_id' => $user->id,
'tenant_id' => $tenant->id,
'is_default' => 1, // 기본 테넌트로 설정
'is_active' => 1, // 활성화
]);
// 5-1. Create UserTenant (tenant-user access mapping)
UserTenant::create([
'user_id' => $user->id,
'tenant_id' => $tenant->id,
'is_default' => 1, // 기본 테넌트로 설정
'is_active' => 1, // 활성화
'joined_at' => now(), // 가입 시각
]);
// 6. Set tenant context for permissions
app()->bind('tenant_id', fn () => $tenant->id);
app(PermissionRegistrar::class)->setPermissionsTeamId($tenant->id);
// 7. Create 'system_manager' role
$role = Role::create([
'tenant_id' => $tenant->id,
'guard_name' => 'api',
'name' => 'system_manager',
'description' => '시스템 관리자',
]);
// 8. Get all permissions created by MenuObserver (menu:{id}.{action} pattern)
$permissionNames = [];
$actions = config('authz.menu_actions', ['view', 'create', 'update', 'delete', 'approve']);
foreach ($menuIds as $menuId) {
foreach ($actions as $action) {
$permissionNames[] = "menu:{$menuId}.{$action}";
}
}
$permissions = Permission::whereIn('name', $permissionNames)
->where('tenant_id', $tenant->id)
->where('guard_name', 'api')
->get();
// 9. Assign all menu permissions to system_manager role
$role->syncPermissions($permissions);
// 10. Assign system_manager role to user
$user->assignRole($role);
// 11. Get created menus
$menus = Menu::whereIn('id', $menuIds)
->orderBy('parent_id')
->orderBy('sort_order')
->get(['id', 'parent_id', 'name', 'url', 'icon', 'sort_order', 'is_external', 'external_url'])
->toArray();
// 12. Return user, tenant, menus, and roles data
return [
'user' => [
'id' => $user->id,
'user_id' => $user->user_id,
'name' => $user->name,
'email' => $user->email,
'phone' => $user->phone,
'options' => $user->options,
],
'tenant' => [
'id' => $tenant->id,
'company_name' => $tenant->company_name,
'business_num' => $tenant->business_num,
'tenant_st_code' => $tenant->tenant_st_code,
'options' => $tenant->options,
],
'menus' => $menus,
'roles' => [
[
'id' => $role->id,
'name' => $role->name,
'description' => $role->description,
],
],
];
});
}
}