Files
musadaq-saas/app/Modules/Auth/AuthService.php

59 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Auth;
use App\Modules\Users\UserModel;
use App\Services\Security\JwtService;
use Exception;
final class AuthService
{
public function __construct(
private readonly UserModel $userModel,
private readonly JwtService $jwtService
) {}
public function login(string $email, string $password): array
{
$user = $this->userModel->findByEmail($email);
if (!$user || !password_verify($password, $user['password_hash'])) {
throw new Exception("البريد الإلكتروني أو كلمة المرور غير صحيحة");
}
if (!$user['is_active']) {
throw new Exception("هذا الحساب معطل حالياً");
}
$accessToken = $this->jwtService->issueAccessToken([
'user_id' => $user['id'],
'tenant_id' => $user['tenant_id'],
'role' => $user['role'],
'assigned_company_id' => $user['assigned_company_id']
]);
$refreshToken = $this->jwtService->issueRefreshToken($user['id']);
// Update refresh token hash in DB
$this->userModel->update($user['id'], [
'refresh_token_hash' => password_hash($refreshToken, PASSWORD_BCRYPT),
'last_login_at' => date('Y-m-d H:i:s'),
'last_login_ip' => $_SERVER['REMOTE_ADDR'] ?? null
]);
return [
'access_token' => $accessToken,
'refresh_token' => $refreshToken,
'user' => [
'id' => $user['id'],
'name' => $user['name'],
'email' => $user['email'],
'role' => $user['role'],
'assigned_company_id' => $user['assigned_company_id']
]
];
}
}