Files
scoutiq/app/Middleware/Authenticate.php

68 lines
2.1 KiB
PHP

<?php
namespace App\Middleware;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Services\Auth\AuthService;
use Exception;
class Authenticate implements MiddlewareInterface
{
private Session $session;
private AuthService $authService;
public function __construct(Session $session, AuthService $authService)
{
$this->session = $session;
$this->authService = $authService;
}
/**
* Authenticate session or JWT bearer token.
*/
public function handle(Request $request, Response $response, callable $next): void
{
$path = $request->getPath();
// 1. API Route Authentication (JWT verification)
if (str_starts_with($path, '/api')) {
$authHeader = $request->getHeader('Authorization');
if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
throw new Exception("Unauthorized. Bearer token missing.", 401);
}
$token = substr($authHeader, 7);
$user = $this->authService->verifyJwt($token);
if (!$user) {
throw new Exception("Unauthorized. Invalid or expired token.", 401);
}
// Inject the authenticated user into route parameters for controller access
$request->setRouteParams(array_merge($request->getRouteParams(), ['_authenticated_user' => $user]));
$next();
return;
}
// 2. Web Route Authentication (Session verification)
$userId = $this->session->get('user_id');
if (!$userId) {
$this->session->setFlash('error', 'Please login to access this page.');
$response->redirect('/login');
return;
}
$user = $this->authService->getUserById($userId);
if (!$user) {
$this->session->destroy();
$response->redirect('/login');
return;
}
// Inject the authenticated user
$request->setRouteParams(array_merge($request->getRouteParams(), ['_authenticated_user' => $user]));
$next();
}
}