implement auth middleware
Green phase: PSR-15 AuthMiddleware checks auth_token cookie, looks up session, validates expiry, sets user attribute on request or returns 401.
This commit is contained in:
parent
db01bfdc2e
commit
b581e80413
1 changed files with 59 additions and 0 deletions
59
backend/app/Middleware/AuthMiddleware.php
Normal file
59
backend/app/Middleware/AuthMiddleware.php
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Middleware;
|
||||||
|
|
||||||
|
use App\Auth\Clock;
|
||||||
|
use App\Auth\SessionRepository;
|
||||||
|
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 AuthMiddleware implements MiddlewareInterface
|
||||||
|
{
|
||||||
|
public const COOKIE_NAME = 'auth_token';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private SessionRepository $sessionRepo,
|
||||||
|
private Clock $clock,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function process(
|
||||||
|
ServerRequestInterface $request,
|
||||||
|
RequestHandlerInterface $handler,
|
||||||
|
): ResponseInterface {
|
||||||
|
$cookies = $request->getCookieParams();
|
||||||
|
$token = $cookies[self::COOKIE_NAME] ?? null;
|
||||||
|
|
||||||
|
if (! is_string($token) || $token === '') {
|
||||||
|
return $this->unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = $this->sessionRepo->findByToken($token);
|
||||||
|
|
||||||
|
if ($session === null) {
|
||||||
|
return $this->unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($session->isExpired($this->clock->now())) {
|
||||||
|
$this->sessionRepo->deleteByToken($token);
|
||||||
|
|
||||||
|
return $this->unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
$request = $request->withAttribute('user', $session->getUser());
|
||||||
|
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function unauthorized(): ResponseInterface
|
||||||
|
{
|
||||||
|
$response = new Response(401);
|
||||||
|
$response->getBody()->write(
|
||||||
|
json_encode(['error' => 'unauthenticated']),
|
||||||
|
);
|
||||||
|
|
||||||
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue