From d8b21b8a8580314a889e784b664c36e3984ab861 Mon Sep 17 00:00:00 2001 From: Dave Smith-Hayes Date: Sun, 16 Jun 2024 21:47:44 -0400 Subject: [PATCH] Check if user has an active session middleware. --- app/src/Controller/User/LoginUserAction.php | 5 +++- .../Middleware/AuthenticatedMiddleware.php | 28 +++++++++++++++++++ app/src/Routes.php | 11 ++++++-- 3 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 app/src/Middleware/AuthenticatedMiddleware.php diff --git a/app/src/Controller/User/LoginUserAction.php b/app/src/Controller/User/LoginUserAction.php index c3f41cb..3d44126 100644 --- a/app/src/Controller/User/LoginUserAction.php +++ b/app/src/Controller/User/LoginUserAction.php @@ -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; } } diff --git a/app/src/Middleware/AuthenticatedMiddleware.php b/app/src/Middleware/AuthenticatedMiddleware.php new file mode 100644 index 0000000..d38f29a --- /dev/null +++ b/app/src/Middleware/AuthenticatedMiddleware.php @@ -0,0 +1,28 @@ +session->has('user')) { + $response = $this->responseFactory->createResponse(403, "Unauthorized"); + return $response; + } + + return $handler->handle($request); + } +} diff --git a/app/src/Routes.php b/app/src/Routes.php index 48dafc7..2f1fe30 100644 --- a/app/src/Routes.php +++ b/app/src/Routes.php @@ -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'); } }