VanguardAI/app/Middleware/AuthorizationMiddleware.php
2024-10-27 12:50:51 -06:00

66 lines
1.5 KiB
PHP

<?php
namespace App\Middleware;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Controllers\ViewController;
class AuthorizationMiddleware
{
private $jwtSecret;
public function __construct()
{
$this->jwtSecret = $_ENV["JWT_SECRET"];
}
public function handle($requestUri, $requestMethod)
{
$routes = include __DIR__ . "/../Config/Routes.php";
$isProtected = $this->isProtectedRoute(
$routes,
$requestUri,
$requestMethod
);
if (!$isProtected) {
// La ruta es pública, permitir acceso
return true;
}
$jwt = $_COOKIE["jwt"] ?? null;
if (!$jwt) {
// El usuario no está logueado, redirigir al login
header("Location: /login");
exit();
}
try {
$decoded = JWT::decode($jwt, new Key($this->jwtSecret, "HS256"));
} catch (\Exception $e) {
// Token inválido, redirigir al login
header("Location: /login");
exit();
}
// Token válido, continuar
return true;
}
private function isProtectedRoute($routes, $requestUri, $requestMethod)
{
foreach ($routes as $route) {
if (
$route["uri"] === $requestUri &&
$route["method"] === $requestMethod
) {
return $route["protected"];
}
}
// Si la ruta no se encuentra, se considera protegida por defecto
return true;
}
}