292 lines
10 KiB
PHP
292 lines
10 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\Auth;
|
|
|
|
use App\Core\{Request, Response};
|
|
use App\Services\Security\EncryptionService;
|
|
use App\Services\Security\JwtService;
|
|
use Throwable;
|
|
|
|
final class AuthController
|
|
{
|
|
public function __construct(private readonly AuthService $authService) {}
|
|
|
|
public function login(Request $request): void
|
|
{
|
|
$email = $request->input('email');
|
|
$password = $request->input('password');
|
|
|
|
if (!$email || !$password) {
|
|
Response::error('يرجى إدخال البريد الإلكتروني وكلمة المرور', 'VALIDATION_ERROR', 422);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$result = $this->authService->login($email, $password);
|
|
|
|
// 2FA Check
|
|
if (($result['user']['totp_enabled'] ?? false) === true) {
|
|
Response::json([
|
|
'success' => true,
|
|
'requires_2fa' => true,
|
|
'temp_token' => $result['access_token']
|
|
]);
|
|
return;
|
|
}
|
|
|
|
$this->setAuthCookies($result);
|
|
|
|
// Backward compatibility for existing non-browser clients
|
|
$responseData = $result;
|
|
unset($responseData['refresh_token']);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => $responseData,
|
|
'message' => 'تم تسجيل الدخول بنجاح'
|
|
]);
|
|
} catch (Throwable $e) {
|
|
Response::error($e->getMessage(), 'AUTH_FAILED', 401);
|
|
}
|
|
}
|
|
|
|
public function me(Request $request): void
|
|
{
|
|
$db = \App\Core\Database::getInstance();
|
|
$stmt = $db->prepare("SELECT id, tenant_id, name, email, role, totp_enabled FROM users WHERE id = ?");
|
|
$stmt->execute([$request->user->user_id]);
|
|
$user = $stmt->fetch();
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => $user
|
|
]);
|
|
}
|
|
|
|
public function logout(Request $request): void
|
|
{
|
|
$authHeader = $request->getHeader('Authorization');
|
|
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
|
|
try {
|
|
$token = substr($authHeader, 7);
|
|
$jwtService = new JwtService();
|
|
$decoded = $jwtService->verifyToken($token);
|
|
$jti = (string)($decoded['jti'] ?? '');
|
|
$remaining = max(((int)($decoded['exp'] ?? 0)) - time(), 0);
|
|
if ($jti !== '') {
|
|
$this->authService->logout($jti, $remaining);
|
|
}
|
|
} catch (Throwable $e) {
|
|
error_log('[AUTH] Could not parse token on logout: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
// Clear auth cookies
|
|
setcookie('refresh_token', '', ['expires' => time() - 3600, 'path' => '/api/v1/auth/refresh', 'httponly' => true, 'samesite' => 'Strict', 'secure' => true]);
|
|
setcookie('access_token', '', ['expires' => time() - 3600, 'path' => '/', 'httponly' => true, 'samesite' => 'Strict', 'secure' => true]);
|
|
setcookie('csrf_token', '', ['expires' => time() - 3600, 'path' => '/', 'httponly' => false, 'samesite' => 'Strict', 'secure' => true]);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'message' => 'تم تسجيل الخروج بنجاح'
|
|
]);
|
|
}
|
|
|
|
public function refresh(Request $request): void
|
|
{
|
|
$refreshToken = $_COOKIE['refresh_token'] ?? null;
|
|
|
|
if (!$refreshToken) {
|
|
Response::error('رمز التجديد مفقود', 'UNAUTHORIZED', 401);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$result = $this->authService->refresh($refreshToken);
|
|
|
|
$this->setAuthCookies($result);
|
|
|
|
// Backward compatibility
|
|
$responseData = $result;
|
|
unset($responseData['refresh_token']);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => $responseData,
|
|
'message' => 'تم تجديد الجلسة بنجاح'
|
|
]);
|
|
} catch (Throwable $e) {
|
|
Response::error($e->getMessage(), 'REFRESH_FAILED', 401);
|
|
}
|
|
}
|
|
public function register(Request $request): void
|
|
{
|
|
try {
|
|
$result = $this->authService->register($request->getBody());
|
|
|
|
$this->setAuthCookies($result);
|
|
|
|
// Backward compatibility
|
|
$responseData = $result;
|
|
unset($responseData['refresh_token']);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => $responseData,
|
|
'message' => 'تم إنشاء الحساب وتسجيل الدخول بنجاح'
|
|
]);
|
|
} catch (Throwable $e) {
|
|
Response::error($e->getMessage(), 'REGISTRATION_FAILED', 400);
|
|
}
|
|
}
|
|
|
|
public function enable2FA(Request $request): void
|
|
{
|
|
$user = $request->user;
|
|
$totpService = new \App\Services\TotpService();
|
|
$secret = $totpService->generateSecret();
|
|
$qrUrl = $totpService->getQrCodeUrl($user->email, $secret);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => [
|
|
'secret' => $secret,
|
|
'qr_url' => $qrUrl
|
|
]
|
|
]);
|
|
}
|
|
|
|
public function verify2FA(Request $request): void
|
|
{
|
|
$data = $request->getBody();
|
|
$code = $data['code'] ?? '';
|
|
$secret = $data['secret'] ?? '';
|
|
|
|
$totpService = new \App\Services\TotpService();
|
|
if ($totpService->verify($secret, $code)) {
|
|
$encryptedSecret = (new EncryptionService())->encrypt($secret);
|
|
$db = \App\Core\Database::getInstance();
|
|
$stmt = $db->prepare("UPDATE users SET totp_secret = ?, totp_enabled = 1 WHERE id = ?");
|
|
$stmt->execute([$encryptedSecret, $request->user->user_id]);
|
|
|
|
Response::json(['success' => true, 'message' => 'تم تفعيل التحقق الثنائي بنجاح']);
|
|
} else {
|
|
Response::error('رمز التحقق غير صحيح', 'INVALID_CODE', 400);
|
|
}
|
|
}
|
|
|
|
public function login2FAVerify(Request $request): void
|
|
{
|
|
$data = $request->getBody();
|
|
$code = $data['code'] ?? '';
|
|
$userId = $request->user->user_id;
|
|
|
|
$db = \App\Core\Database::getInstance();
|
|
$stmt = $db->prepare("SELECT totp_secret FROM users WHERE id = ?");
|
|
$stmt->execute([$userId]);
|
|
$secret = $stmt->fetchColumn();
|
|
|
|
if (!$secret) {
|
|
Response::error('لم يتم تفعيل التحقق الثنائي لهذا الحساب', 'TWO_FA_DISABLED', 400);
|
|
return;
|
|
}
|
|
|
|
$totpService = new \App\Services\TotpService();
|
|
$decrypted = null;
|
|
try {
|
|
$decrypted = (new EncryptionService())->decrypt((string)$secret);
|
|
} catch (Throwable $e) {
|
|
// Backward compatibility with old plaintext records
|
|
$decrypted = (string)$secret;
|
|
}
|
|
|
|
if (!$totpService->verify($decrypted, $code)) {
|
|
Response::error('رمز التحقق غير صحيح', 'INVALID_CODE', 401);
|
|
return;
|
|
}
|
|
|
|
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
|
|
$stmt->execute([$userId]);
|
|
$user = $stmt->fetch();
|
|
if (!$user) {
|
|
Response::error('المستخدم غير موجود', 'NOT_FOUND', 404);
|
|
return;
|
|
}
|
|
|
|
$result = $this->authService->createSession($user);
|
|
$this->setAuthCookies($result);
|
|
|
|
$responseData = $result;
|
|
unset($responseData['refresh_token']);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => $responseData,
|
|
'message' => 'تم التحقق وتأسيس الجلسة بنجاح'
|
|
]);
|
|
}
|
|
|
|
public function disable2FA(Request $request): void
|
|
{
|
|
$password = (string)$request->input('password', '');
|
|
if ($password === '') {
|
|
Response::error('كلمة المرور مطلوبة لتعطيل التحقق الثنائي', 'VALIDATION_ERROR', 422);
|
|
return;
|
|
}
|
|
|
|
$db = \App\Core\Database::getInstance();
|
|
$stmt = $db->prepare("SELECT password_hash FROM users WHERE id = ?");
|
|
$stmt->execute([$request->user->user_id]);
|
|
$hash = $stmt->fetchColumn();
|
|
if (!$hash || !password_verify($password, (string)$hash)) {
|
|
Response::error('كلمة المرور غير صحيحة', 'UNAUTHORIZED', 401);
|
|
return;
|
|
}
|
|
|
|
$db = \App\Core\Database::getInstance();
|
|
$stmt = $db->prepare("UPDATE users SET totp_secret = NULL, totp_enabled = 0 WHERE id = ?");
|
|
$stmt->execute([$request->user->user_id]);
|
|
|
|
Response::json(['success' => true, 'message' => 'تم تعطيل التحقق الثنائي']);
|
|
}
|
|
|
|
private function setAuthCookies(array $result): void
|
|
{
|
|
$cookieDomain = $_SERVER['HTTP_HOST'] ?? '';
|
|
$secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
|
|
|
|
// 1. Refresh Token (HttpOnly, scoped to /refresh)
|
|
setcookie('refresh_token', $result['refresh_token'] ?? '', [
|
|
'expires' => time() + (60 * 60 * 24 * 7), // 7 days
|
|
'path' => '/api/v1/auth/refresh',
|
|
'domain' => $cookieDomain,
|
|
'httponly' => true,
|
|
'samesite' => 'Strict',
|
|
'secure' => $secure
|
|
]);
|
|
|
|
// 2. Access Token (HttpOnly, scoped to /)
|
|
setcookie('access_token', $result['access_token'] ?? '', [
|
|
'expires' => time() + (60 * 15), // 15 mins
|
|
'path' => '/',
|
|
'domain' => $cookieDomain,
|
|
'httponly' => true,
|
|
'samesite' => 'Strict',
|
|
'secure' => $secure
|
|
]);
|
|
|
|
// 3. CSRF Token (Readable by JS)
|
|
$csrfToken = bin2hex(random_bytes(32));
|
|
setcookie('csrf_token', $csrfToken, [
|
|
'expires' => time() + (60 * 15),
|
|
'path' => '/',
|
|
'domain' => $cookieDomain,
|
|
'httponly' => false,
|
|
'samesite' => 'Strict',
|
|
'secure' => $secure
|
|
]);
|
|
}
|
|
}
|