- 이메일 또는 아이디로 로그인 가능 - 아이디 로그인은 본사(HQ) 소속 직원만 허용 - LoginRequest에 isEmail(), getLoginField(), getCredentials() 메서드 추가 - AuthService.login()에 loginField 파라미터 추가 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
162 lines
4.7 KiB
PHP
162 lines
4.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class AuthService
|
|
{
|
|
/**
|
|
* 로그인 실패 사유
|
|
*/
|
|
private ?string $loginError = null;
|
|
|
|
public function __construct(
|
|
private readonly ApiTokenService $apiTokenService
|
|
) {}
|
|
|
|
/**
|
|
* 웹 세션 로그인
|
|
* - 이메일 로그인: 본사(HQ) 테넌트 소속만 허용
|
|
* - 아이디 로그인: 본사(HQ) 테넌트 소속만 허용
|
|
*
|
|
* @param array $credentials 인증 정보 ['email' => ..., 'password' => ...] 또는 ['user_id' => ..., 'password' => ...]
|
|
* @param bool $remember 로그인 유지 여부
|
|
* @param string $loginField 로그인 필드 ('email' 또는 'user_id')
|
|
*/
|
|
public function login(array $credentials, bool $remember = false, string $loginField = 'email'): bool
|
|
{
|
|
$this->loginError = null;
|
|
|
|
// 아이디 로그인인 경우 사전 검증
|
|
if ($loginField === 'user_id') {
|
|
$user = User::where('user_id', $credentials['user_id'])->first();
|
|
|
|
if (! $user) {
|
|
$this->loginError = '아이디 또는 비밀번호가 올바르지 않습니다.';
|
|
return false;
|
|
}
|
|
|
|
// 아이디 로그인은 본사 소속만 허용
|
|
if (! $user->belongsToHQ()) {
|
|
$this->loginError = '아이디 로그인은 본사 소속 직원만 가능합니다.';
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// 1. 기본 인증 시도
|
|
if (! Auth::attempt($credentials, $remember)) {
|
|
$this->loginError = $loginField === 'email'
|
|
? '이메일 또는 비밀번호가 올바르지 않습니다.'
|
|
: '아이디 또는 비밀번호가 올바르지 않습니다.';
|
|
|
|
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();
|
|
}
|
|
}
|