add auth middleware
This commit is contained in:
parent
cd2168c822
commit
d549cf914f
1 changed files with 84 additions and 0 deletions
84
app/Auth/AuthMiddleware.php
Normal file
84
app/Auth/AuthMiddleware.php
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
<?php
|
||||
|
||||
namespace App\Auth;
|
||||
|
||||
use App\User\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 AuthMiddleware implements MiddlewareInterface
|
||||
{
|
||||
public const COOKIE_NAME = 'auth_token';
|
||||
|
||||
public function __construct(
|
||||
private SessionRepository $sessionRepo,
|
||||
private UserRepository $userRepo,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
public function process(
|
||||
ServerRequestInterface $request,
|
||||
RequestHandlerInterface $handler,
|
||||
): ResponseInterface {
|
||||
$cookies = $request->getCookieParams();
|
||||
$token = $cookies[self::COOKIE_NAME] ?? null;
|
||||
|
||||
if ($token === null) {
|
||||
return $this->unauthorized($request);
|
||||
}
|
||||
|
||||
$session = $this->sessionRepo->findByToken($token);
|
||||
if ($session === null) {
|
||||
return $this->unauthorized($request);
|
||||
}
|
||||
|
||||
if ($session->isExpired($this->clock->now())) {
|
||||
$this->sessionRepo->deleteByToken($token);
|
||||
return $this->unauthorized($request);
|
||||
}
|
||||
|
||||
$user = $this->userRepo->find($session->getUserId());
|
||||
if ($user === null) {
|
||||
return $this->unauthorized($request);
|
||||
}
|
||||
|
||||
return $handler->handle(
|
||||
$request->withAttribute('user', $user)
|
||||
);
|
||||
}
|
||||
|
||||
private function unauthorized(
|
||||
ServerRequestInterface $request
|
||||
): ResponseInterface {
|
||||
if ($this->wantsJson($request)) {
|
||||
$response = new Response(401);
|
||||
$response->getBody()->write(
|
||||
json_encode(['error' => 'unauthenticated'])
|
||||
);
|
||||
return $response->withHeader(
|
||||
'Content-Type',
|
||||
'application/json'
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(302)->withHeader('Location', '/login');
|
||||
}
|
||||
|
||||
private function wantsJson(ServerRequestInterface $request): bool
|
||||
{
|
||||
$path = $request->getUri()->getPath();
|
||||
if (str_starts_with($path, '/api/')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$accept = $request->getHeaderLine('Accept');
|
||||
if (str_contains($accept, 'application/json')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue