Check if user has an active session middleware.

This commit is contained in:
Dave Smith-Hayes 2024-06-16 21:47:44 -04:00
parent 2b75ea2dea
commit d8b21b8a85
3 changed files with 41 additions and 3 deletions

View File

@ -34,7 +34,10 @@ class LoginUserAction extends Controller
}
// start the session
$this->session->set('user', [ 'id' => $user->getId() ]);
$this->session->set('user', [
'id' => $user->getId(),
'authenticated' => true
]);
return $this->response;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace Slovocast\Middleware;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ResponseFactoryInterface;
use Odan\Session\SessionInterface;
class AuthenticatedMiddleware implements MiddlewareInterface
{
public function __construct(
private SessionInterface $session,
private ResponseFactoryInterface $responseFactory
) {}
public function process(Request $request, RequestHandler $handler): Response
{
if (!this->session->has('user')) {
$response = $this->responseFactory->createResponse(403, "Unauthorized");
return $response;
}
return $handler->handle($request);
}
}

View File

@ -7,9 +7,13 @@ use Slovocast\Controller\HomePage;
use Slovocast\Controller\User\{
RegisterUserPage,
RegisterUserAction,
LoginUserPage
LoginUserPage,
LoginUserAction
};
use Slovocast\Middleware\{
VerifyPasswordMiddleware,
AuthenticatedMiddleware
};
use Slovocast\Middleware\VerifyPasswordMiddleware;
class Routes
{
@ -30,5 +34,8 @@ class Routes
$app->get('/login', LoginUserPage::class)
->setName('user-login-page');
$app->post('/login', LoginUserAction::class)
->add(AuthenticatedMiddleware::class)
->setName('user-login-action');
}
}