Files
server/core/lib/Http/Middleware/RouterMiddleware.php
2026-02-10 18:46:11 -05:00

63 lines
1.9 KiB
PHP

<?php
namespace KTXC\Http\Middleware;
use KTXC\Http\Request\Request;
use KTXC\Http\Response\Response;
use KTXC\Routing\Router;
use KTXC\Routing\Route;
use KTXC\SessionIdentity;
use KTXC\Security\Authorization\PermissionChecker;
/**
* Router middleware
* Matches routes and dispatches to controllers
*/
class RouterMiddleware implements MiddlewareInterface
{
public function __construct(
private readonly Router $router,
private readonly SessionIdentity $sessionIdentity,
private readonly PermissionChecker $permissionChecker
) {}
public function process(Request $request, RequestHandlerInterface $handler): Response
{
// Attempt to match the route
$match = $this->router->match($request);
if (!$match instanceof Route) {
// No route matched, continue to next handler (will return 404)
return $handler->handle($request);
}
// Check if route requires authentication
if ($match->authenticated && $this->sessionIdentity->identity() === null) {
return new Response(
Response::$statusTexts[Response::HTTP_UNAUTHORIZED],
Response::HTTP_UNAUTHORIZED
);
}
// Check permissions (if any specified)
if ($match->authenticated && !empty($match->permissions)) {
if (!$this->permissionChecker->canAny($match->permissions)) {
return new Response(
Response::$statusTexts[Response::HTTP_FORBIDDEN],
Response::HTTP_FORBIDDEN
);
}
}
// Dispatch to the controller
$response = $this->router->dispatch($match, $request);
if ($response instanceof Response) {
return $response;
}
// If dispatch didn't return a response, continue to next handler
return $handler->handle($request);
}
}