Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
routes: add a logout route and a session middleware
app/controllers/AuthController.php | 22 ++++++++++++++++++++++ app/helpers/SessionMiddleware.php | 20 ++++++++++++++++++++ bootstrap.php | 4 ++++ config/routes.php | 12 ++++++++++++
diff --git a/app/controllers/AuthController.php b/app/controllers/AuthController.php index dbc9c9310e0d8c6e0c1931bc65f0986e81f34712..4f97c0399016d9c89b2a558ecb13301d39c25afe 100644 --- a/app/controllers/AuthController.php +++ b/app/controllers/AuthController.php @@ -59,4 +59,26 @@ // TODO: Flash messages echo 'Erro ao cadastrar usuário'; } } + + public function logout() { + $_SESSION = []; + session_destroy(); + + if (ini_get("session.use_cookies")) { + $params = session_get_cookie_params(); + setcookie( + session_name(), + '', + time() - 42000, + $params["path"], + $params["domain"], + $params["secure"], + $params["httponly"] + ); + } + + header('Location: /'); + + exit(); + } } diff --git a/app/helpers/SessionMiddleware.php b/app/helpers/SessionMiddleware.php new file mode 100644 index 0000000000000000000000000000000000000000..c7ca6629db28a8cfe2808c7aae8cefe923027705 --- /dev/null +++ b/app/helpers/SessionMiddleware.php @@ -0,0 +1,20 @@ +<?php + +function sessionMiddleware($currentRoute) { + $publicRoutes = ['/login', '/register', '/']; + + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + if (isset($_SESSION['user_id']) && in_array($currentRoute, $publicRoutes)) { + header('Location: /dashboard'); + exit; + } + + if (!isset($_SESSION['user_id']) && !in_array($currentRoute, $publicRoutes)) { + header('Location: /login'); + exit; + } +} + diff --git a/bootstrap.php b/bootstrap.php index 3b36292fb11d952d5dfdbce49f896a1bcdd23ca2..46cf5b0b92d7fddfb30c0a0cf814f359eaeb4dfc 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -7,6 +7,10 @@ session_start(); require_once 'config/database.php'; +require_once __DIR__ . '/app/helpers/SessionMiddleware.php'; $app = require_once 'config/routes.php'; + +$currentRoute = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); +sessionMiddleware($currentRoute); echo $app(); diff --git a/config/routes.php b/config/routes.php index 2480e43aac27f2c4d03bc48f5eaa618c2e8a42d3..b84b48c31c62cf39ed8726954f370a78eef2d068 100644 --- a/config/routes.php +++ b/config/routes.php @@ -11,14 +11,26 @@ // TODO: Meio burro isso if ($uri === '') { return (new HelloController())->index(); + + // POST /login } elseif ($uri === 'login' && $method === 'POST') { return (new AuthController())->login(); + + // GET /login } elseif ($uri === 'login') { return (new HelloController())->login(); + + // POST /register } elseif ($uri === 'register' && $method === 'POST') { return (new AuthController())->register(); + + // GET /register } elseif ($uri === 'register') { return (new HelloController())->register(); + + // GET /logout + } elseif ($uri === 'logout') { + return (new AuthController())->logout(); } http_response_code(404);