108 lines
4.6 KiB
PHP
108 lines
4.6 KiB
PHP
<?php
|
|
|
|
namespace App\Middlewares;
|
|
|
|
use App\Core\Request;
|
|
use App\Core\Response;
|
|
use App\Core\Security;
|
|
use App\Core\RedisClient;
|
|
use App\Core\Database;
|
|
|
|
class AuthMiddleware
|
|
{
|
|
/**
|
|
* Verifies the JWT token and populates request properties.
|
|
*/
|
|
public function handle(Request $request, Response $response): void
|
|
{
|
|
$token = null;
|
|
$authHeader = $request->getHeader('authorization', '');
|
|
|
|
if ($authHeader && preg_match('/Bearer\s(\S+)/i', $authHeader, $matches)) {
|
|
$token = $matches[1];
|
|
} else {
|
|
$queryToken = $request->getQuery('token');
|
|
if (!empty($queryToken)) {
|
|
$token = trim((string)$queryToken);
|
|
}
|
|
}
|
|
|
|
if (!$token) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'Token not provided or invalid format']);
|
|
exit;
|
|
}
|
|
$payload = Security::verifyJWT($token);
|
|
|
|
if (!$payload) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'Invalid or expired token']);
|
|
exit;
|
|
}
|
|
|
|
// Validate required custom payload elements
|
|
if (!isset($payload['user_id']) || !isset($payload['role'])) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'Malformed token payload structure']);
|
|
exit;
|
|
}
|
|
|
|
$userId = (int)$payload['user_id'];
|
|
$role = (string)($payload['role'] ?? 'student');
|
|
|
|
$identityId = (int)($payload['identity_id'] ?? 0);
|
|
$tokenVersion = (int)($payload['token_version'] ?? 0);
|
|
if ($identityId <= 0 || $tokenVersion <= 0) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'جلسة قديمة؛ يرجى تسجيل الدخول مجدداً']);
|
|
exit;
|
|
}
|
|
|
|
$identity = Database::selectOne(
|
|
"SELECT status, token_version FROM auth_identities WHERE id = ? LIMIT 1",
|
|
[$identityId]
|
|
);
|
|
if (!$identity || $identity['status'] !== 'active' || (int)$identity['token_version'] !== $tokenVersion) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'تم إلغاء الجلسة أو إيقاف الحساب']);
|
|
exit;
|
|
}
|
|
|
|
$requestFingerprint = trim((string)$request->getHeader('x-device-fingerprint', ''));
|
|
$tokenFingerprint = (string)($payload['device_fingerprint'] ?? '');
|
|
if ($requestFingerprint !== '' && $tokenFingerprint !== '' && !hash_equals($tokenFingerprint, $requestFingerprint)) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'بصمة الجهاز لا تطابق الجلسة']);
|
|
exit;
|
|
}
|
|
|
|
// Check if session is active in Redis (Role-isolated single active session tracking)
|
|
try {
|
|
$redis = RedisClient::getInstance();
|
|
$sessionData = $redis->get("active_session:{$role}:{$userId}") ?: $redis->get("active_session:{$userId}");
|
|
|
|
if (!$sessionData) {
|
|
$response->status(401)->json(['error' => 'Unauthorized', 'message' => 'الجلسة غير نشطة؛ يرجى تسجيل الدخول مجدداً']);
|
|
exit;
|
|
}
|
|
$session = json_decode($sessionData, true);
|
|
$expectedSig = substr($token, -32);
|
|
if (!is_array($session) || !isset($session['token_signature']) || !hash_equals($session['token_signature'], $expectedSig)) {
|
|
$response->status(401)->json([
|
|
'error' => 'Unauthorized',
|
|
'message' => 'تم تسجيل الدخول من جهاز أو متصفح آخر. يرجى إعادة تسجيل الدخول.'
|
|
]);
|
|
exit;
|
|
}
|
|
} catch (\Exception $e) {
|
|
error_log("AuthMiddleware Redis failure: " . $e->getMessage());
|
|
$response->status(503)->json(['error' => 'Service unavailable', 'message' => 'تعذر التحقق من الجلسة مؤقتاً']);
|
|
exit;
|
|
}
|
|
|
|
// Attach user info to the Request instance dynamically so controllers can use it
|
|
$request->user_id = $userId;
|
|
$request->role = $payload['role'];
|
|
$request->uuid = $payload['uuid'] ?? null;
|
|
$request->school_id = isset($payload['school_id']) ? (int)$payload['school_id'] : null;
|
|
$request->directorate_id = isset($payload['directorate_id']) ? (int)$payload['directorate_id'] : null;
|
|
$request->full_name = isset($payload['name']) ? (string)$payload['name'] : null;
|
|
$request->identity_id = $identityId;
|
|
$request->is_super_admin = $role === 'super_admin';
|
|
}
|
|
}
|