loginError = null; // 1. 기본 인증 시도 if (! Auth::attempt($credentials, $remember)) { $this->loginError = '이메일 또는 비밀번호가 올바르지 않습니다.'; return false; } // 2. 본사(HQ) 테넌트 소속 확인 $user = Auth::user(); if (! $user->belongsToHQ()) { Auth::logout(); $this->loginError = '본사 소속 직원만 관리자 패널에 접근할 수 있습니다.'; return false; } // 3. 활성 상태 확인 if (! $user->is_active) { Auth::logout(); $this->loginError = '비활성화된 계정입니다. 관리자에게 문의하세요.'; return false; } // 4. 로그인 성공 시 HQ 테넌트를 기본 선택 $hqTenant = $user->getHQTenant(); if ($hqTenant) { session(['selected_tenant_id' => $hqTenant->id]); // 5. API 서버 토큰 교환 (FCM 등 API 호출용) $this->exchangeApiToken($user->id, $hqTenant->id); } return true; } /** * API 서버 토큰 교환 * 실패해도 로그인은 허용 (FCM 기능만 제한됨) * * @param int $userId 사용자 ID * @param int $tenantId 테넌트 ID */ private function exchangeApiToken(int $userId, int $tenantId): void { try { $result = $this->apiTokenService->exchangeToken($userId, $tenantId); if ($result['success']) { $this->apiTokenService->storeTokenInSession( $result['data']['access_token'], $result['data']['expires_in'] ); Log::info('[AuthService] API token exchanged', ['user_id' => $userId]); } else { Log::warning('[AuthService] API token exchange failed', [ 'user_id' => $userId, 'error' => $result['error'] ?? 'Unknown error', ]); } } catch (\Exception $e) { Log::error('[AuthService] API token exchange exception', [ 'user_id' => $userId, 'exception' => $e->getMessage(), ]); } } /** * 마지막 로그인 실패 사유 조회 */ public function getLoginError(): ?string { return $this->loginError; } /** * 로그아웃 */ public function logout(): void { // API 토큰 정리 $this->apiTokenService->clearSessionToken(); Auth::logout(); } /** * API 토큰 생성 (향후 사용) */ public function createToken(array $credentials): ?string { $user = User::where('email', $credentials['email'])->first(); if (! $user || ! Hash::check($credentials['password'], $user->password)) { return null; } return $user->createToken('mng-token')->plainTextToken; } /** * 현재 인증된 사용자 정보 */ public function user(): ?User { return Auth::user(); } }