Update: 2026-05-03 17:32:57

This commit is contained in:
Hamza-Ayed
2026-05-03 17:32:57 +03:00
parent 6a3e66ad49
commit 4b40b1185f
102 changed files with 525 additions and 11371 deletions

View File

@@ -1,53 +1,34 @@
<?php
/**
* Simple Authentication Middleware
*/
declare(strict_types=1);
namespace App\Middleware;
use App\Core\{Request, Response};
use App\Services\Security\JwtService;
use Exception;
use App\Core\JWT;
final class AuthMiddleware
{
public function __construct(private readonly JwtService $jwtService) {}
public function handle(Request $request, callable $next): mixed
public static function check(): array
{
$authHeader = $request->getHeader('Authorization');
if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
Response::error('يجب تسجيل الدخول للوصول إلى هذا المورد', 'UNAUTHORIZED', 401);
return null;
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!str_starts_with($authHeader, 'Bearer ')) {
json_error('Unauthorized: Missing or invalid token', 401);
}
$token = substr($authHeader, 7);
try {
$decoded = $this->jwtService->verifyToken($token);
// Check if JTI is blacklisted
$jti = $decoded['jti'] ?? null;
if ($jti) {
try {
$redis = \App\Core\Redis::getInstance();
if ($redis->exists('jwt_blacklist:' . $jti)) {
Response::error('الجلسة منتهية، يرجى تسجيل الدخول من جديد', 'TOKEN_REVOKED', 401);
return null;
}
} catch (\Throwable $e) {
// Redis down — allow (fail open, log security event)
error_log('[AUTH] JWT blacklist check failed: ' . $e->getMessage());
}
}
$request->user = (object) $decoded;
$request->tenantId = $decoded['tenant_id'] ?? null;
} catch (Exception $e) {
Response::error('جلسة العمل منتهية أو غير صالحة', 'UNAUTHORIZED', 401);
return null;
$secret = env('JWT_SECRET');
$decoded = JWT::decode($token, $secret);
if (!$decoded) {
json_error('Unauthorized: Invalid or expired token', 401);
}
return $next($request);
return $decoded;
}
}