phpcbf auto-fixes: string concatenation spacing, single-line class braces, closing brace placement.
60 lines
1.5 KiB
PHP
60 lines
1.5 KiB
PHP
<?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');
|
|
}
|
|
}
|