baleen/src/Session/LoginMiddleware.php

37 lines
1.0 KiB
PHP

<?php
namespace Lewisdale\App\Session;
use Lewisdale\App\Models\Repositories\UserRepository;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;
class LoginMiddleware implements MiddlewareInterface {
function __construct(
private readonly UserRepository $users,
) {}
private function redirectToLogin(): ResponseInterface {
$response = new Response(302);
return $response->withHeader('Location', '/account/login');
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if (!isset($_SESSION['user'])) {
return $this->redirectToLogin();
}
$user = $this->users->find($_SESSION['user']);
if (!$user) {
return $this->redirectToLogin();
}
return $handler->handle($request->withAttribute('user', $user));
}
}