38 lines
1.0 KiB
PHP
38 lines
1.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Middleware;
|
|
|
|
use App\Core\{Request, Response};
|
|
use App\Services\Security\JwtService;
|
|
use Exception;
|
|
|
|
final class AuthMiddleware
|
|
{
|
|
public function __construct(private readonly JwtService $jwtService) {}
|
|
|
|
public function handle(Request $request, callable $next): mixed
|
|
{
|
|
$authHeader = $request->getHeader('Authorization');
|
|
|
|
if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
|
|
Response::error('يجب تسجيل الدخول للوصول إلى هذا المورد', 'UNAUTHORIZED', 401);
|
|
return null;
|
|
}
|
|
|
|
$token = substr($authHeader, 7);
|
|
|
|
try {
|
|
$decoded = $this->jwtService->verifyToken($token);
|
|
$request->user = (object) $decoded;
|
|
$request->tenantId = $decoded['tenant_id'] ?? null;
|
|
} catch (Exception $e) {
|
|
Response::error('جلسة العمل منتهية أو غير صالحة', 'UNAUTHORIZED', 401);
|
|
return null;
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
}
|