Lab 9: Login & Authentication
Additional Resources
Section titled “Additional Resources”- Login System Overview
- User Login
- User Logout
- Middleware in Slim 4
- PHP password_verify() ↗
- OWASP Authentication Cheat Sheet ↗
- OWASP Session Management Cheat Sheet ↗
Overview
Section titled “Overview”In this lab, you will make the login form from Lab 8 work, keep the logged-in user in the session, and protect routes with middleware. Your e-commerce site gets two protected areas:
- The user dashboard, available to any logged-in user.
- The admin panel from Lab 3, available only to administrators.
A later lab uses the same AuthMiddleware to require a login before checkout.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Verify passwords with
password_verify(). - Log users in and out using
SessionManager, issuing a new session ID each time to prevent session fixation. - Build middleware that protects routes (
AuthMiddleware,AdminAuthMiddleware). - Implement role-based access control (admin vs. customer).
- Create a dashboard that only logged-in users can see.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 8: User Registration, including the
UserModel, theAuthController, the login view, and flash messages in the public header. - Completed Lab 4: Session Middleware and Flash Messages, with
SessionMiddlewareregistered for the whole application. - Completed Lab 3: Building an Admin Panel, including the
/adminroute group and theadmin.dashboardroute.
Step 1: Add verifyCredentials() to the UserModel
Section titled “Step 1: Add verifyCredentials() to the UserModel”Objective: Add a method that checks an email or username and a password against the database.
Instructions:
- Open
app/Domain/Models/UserModel.php - Add the following method:
/** * Verify user credentials by email/username and password. * * @param string $identifier Email or username * @param string $password Plain-text password to verify * @return array|null User data if credentials are valid, null otherwise */public function verifyCredentials(string $identifier, string $password): ?array{ // TODO: Look up the user by their identifier (try email first, then username). // If found, verify the password against the stored hash. // Return the user data on success or null on failure.}- Implement the method
- Save the file
Hints:
- Use the
findByEmail()andfindByUsername()methods from Lab 8. password_verify($password, $user['password_hash'])returnstruewhen the password matches the stored hash.- Return
nullfor every failure, whether the user does not exist or the password is wrong. The caller cannot tell the two cases apart, so neither can an attacker.
Step 2: Add regenerate() to the SessionManager
Section titled “Step 2: Add regenerate() to the SessionManager”Objective: Add a method that issues a new session ID, to call at login and logout.
A session fixation attack works like this: an attacker gets the victim’s browser to use a session ID that the attacker already knows, then waits for the victim to log in. If the application keeps the same session ID after login, the attacker’s copy of the ID is now a logged-in session. Issuing a new session ID at login makes the known ID worthless. The 15-minute regeneration in SessionManager::start() does not protect against this, because the old ID can stay valid for up to 15 minutes after login.
Instructions:
- Open
app/Helpers/SessionManager.php - Add the following method after
destroy():
/** * Issue a new session ID and delete the old session. * * Call this whenever the user's privilege level changes (login and logout). */public static function regenerate(): void{ session_regenerate_id(true); $_SESSION['last_regeneration'] = time();}- Save the file
Passing true to session_regenerate_id() deletes the old session file, so the old ID stops working immediately. The session data is copied to the new ID.
Step 3: Add Login and Logout Logic to the AuthController
Section titled “Step 3: Add Login and Logout Logic to the AuthController”Objective: Process the login form, store the user in the session, and log users out.
Instructions:
- Open
app/Controllers/AuthController.php - Add the following import at the top:
use App\Helpers\SessionManager;- Replace the
login()method from Lab 8 with the following version, and add theauthenticate()andlogout()methods:
/** * Display the login form (GET /login). */public function login(Request $request, Response $response, array $args): Response{ // TODO: If a failed login attempt left an identifier in the session, // take it out of the session so it is only used once.
// TODO: Render the login view with the title 'Login' and that identifier // (an empty string if there is none).}
/** * Process the login form (POST /login). */public function authenticate(Request $request, Response $response, array $args): Response{ // TODO: Read the identifier and the password from the submitted form.
// TODO: If a field is empty or the credentials are invalid, remember the // identifier in the session for login(), show "Invalid credentials.", // and send the user back to the login form.
// TODO: Protect the new login against session fixation (see Step 2).
// TODO: Store the user in the session (see the Session Keys table below).
// TODO: Welcome the user and send them to the dashboard that matches their role.}
/** * Log the current user out (POST /logout). */public function logout(Request $request, Response $response, array $args): Response{ // TODO: End the logged-in session without losing the next flash message // (see the note below).
// TODO: Show "You have been logged out." and send the user to the login form.}- Implement every method marked
// TODO - Save the file
Session Keys:
authenticate() stores the following keys. The middleware, the dashboard, and the admin panel read these exact names.
| Key | Value |
|---|---|
user_id | $user['id'] |
user_email | $user['email'] |
user_name | The first and last name, separated by a space |
user_role | $user['role'] ('admin' or 'customer') |
is_authenticated | true |
Never store the password hash in the session.
Hints:
- A failed login redirects back to the login page, like any other POST. Only the identifier is kept for the next request; the password is never sent back to the browser.
- The route names you need are in Lab 3 and in Step 8 of this lab.
Step 4: Create the AuthMiddleware
Section titled “Step 4: Create the AuthMiddleware”Objective: Create a middleware that only lets logged-in users through.
AuthMiddleware runs before the route handler. It checks the session and either lets the request continue or redirects to the login page.
Instructions:
- Navigate to your
app/Middleware/directory - Create a new file named
AuthMiddleware.php - Start from the following class structure:
<?php
namespace App\Middleware;
use App\Helpers\FlashMessage;use App\Helpers\SessionManager;use Psr\Http\Message\ResponseFactoryInterface;use Psr\Http\Message\ResponseInterface as Response;use Psr\Http\Message\ServerRequestInterface as Request;use Psr\Http\Server\MiddlewareInterface;use Psr\Http\Server\RequestHandlerInterface as RequestHandler;use Slim\Routing\RouteContext;
class AuthMiddleware implements MiddlewareInterface{ public function __construct(private ResponseFactoryInterface $responseFactory) { }
/** * Process the request - check if user is authenticated. */ public function process(Request $request, RequestHandler $handler): Response { // TODO: Read 'is_authenticated' from the session. // If the user is not authenticated, add an error flash message and redirect to the login page. // If the user is authenticated, pass the request on with $handler->handle($request). // // Use the following to generate the login URL and create a redirect response: // $routeParser = RouteContext::fromRequest($request)->getRouteParser(); // $loginUrl = $routeParser->urlFor('auth.login'); // $response = $this->responseFactory->createResponse(302); // return $response->withHeader('Location', $loginUrl); }}- Implement the
process()method - Save the file
A middleware is not a controller, so it cannot use the BaseController’s redirect() method. It builds the redirect response itself with the response factory.
Step 5: Create the AdminAuthMiddleware
Section titled “Step 5: Create the AdminAuthMiddleware”Objective: Create a middleware that only lets logged-in administrators through.
AdminAuthMiddleware performs two checks: the user is logged in, and the user’s role is admin. Logged-in customers are redirected to their dashboard.
Instructions:
- Inside
app/Middleware/, create a file namedAdminAuthMiddleware.php - Start from the following class structure:
<?php
namespace App\Middleware;
use App\Helpers\FlashMessage;use App\Helpers\SessionManager;use Psr\Http\Message\ResponseFactoryInterface;use Psr\Http\Message\ResponseInterface as Response;use Psr\Http\Message\ServerRequestInterface as Request;use Psr\Http\Server\MiddlewareInterface;use Psr\Http\Server\RequestHandlerInterface as RequestHandler;use Slim\Routing\RouteContext;
class AdminAuthMiddleware implements MiddlewareInterface{ public function __construct(private ResponseFactoryInterface $responseFactory) { }
/** * Process the request - check if user is authenticated AND is an admin. */ public function process(Request $request, RequestHandler $handler): Response { // TODO: Read 'is_authenticated' and 'user_role' from the session. // If the user is not authenticated, add an error flash message and redirect to 'auth.login'. // If the user is authenticated but not an admin, add the error flash message // "Access denied." and redirect to 'user.dashboard'. // If both checks pass, pass the request on with $handler->handle($request). // // Use the same redirect pattern as AuthMiddleware (RouteParser + responseFactory). }}- Implement the
process()method - Save the file
Step 6: Create the User Dashboard
Section titled “Step 6: Create the User Dashboard”Objective: Create a page that displays the logged-in user’s information.
Instructions:
- Navigate to your
app/Views/directory and create auser/folder - Inside
app/Views/user/, create a file nameddashboard.php - Copy and paste the following code:
<?php
use App\Helpers\SessionManager;use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);?>
<h1>User Dashboard</h1>
<div class="row"> <div class="col-md-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">My Profile</h5> <p class="card-text"> <strong>Name:</strong> <?= hs(SessionManager::get('user_name', 'N/A')) ?><br> <strong>Email:</strong> <?= hs(SessionManager::get('user_email', 'N/A')) ?><br> <strong>Role:</strong> <?= hs(SessionManager::get('user_role', 'N/A')) ?> </p> </div> </div> </div>
<div class="col-md-8"> <div class="card"> <div class="card-body"> <h5 class="card-title">Quick Actions</h5> <div class="d-grid gap-2"> <a href="<?= APP_BASE_URL ?>/" class="btn btn-primary">Browse Products</a> <form method="POST" action="<?= APP_BASE_URL ?>/logout"> <button type="submit" class="btn btn-outline-secondary w-100">Logout</button> </form> </div> </div> </div> </div></div>
<?php ViewHelper::loadFooter(); ?>- Save the file
- Add the following method to
AuthController.php:
/** * Display the user dashboard (GET /dashboard, protected). */public function dashboard(Request $request, Response $response, array $args): Response{ // TODO: Render 'user/dashboard.php' with 'title' => 'Dashboard'}- Implement the method and save the file
Logout is a button inside a POST form, not a link, because logging out changes state. The flash messages render through the public header you updated in Lab 8.
Step 7: Show the Logged-In Admin’s Name
Section titled “Step 7: Show the Logged-In Admin’s Name”Objective: Display the real user’s name in the admin panel instead of the default “Admin”.
In Labs 3 and 4, the admin controllers pass $_SESSION['username'] ?? 'Admin' to the admin header. Nothing sets a username key, so the header always shows “Admin”. The name is now stored under user_name.
Instructions:
- Open
app/Controllers/AdminDashboardController.php - In the
dashboard()method, replace$_SESSION['username'] ?? 'Admin'withSessionManager::get('user_name', 'Admin') - Add
use App\Helpers\SessionManager;at the top of the file - Make the same two changes in the
index()method ofapp/Controllers/FlashDemoController.php - Save both files
Step 8: Register the Routes
Section titled “Step 8: Register the Routes”Objective: Add the login, logout, and dashboard routes, and protect the dashboard and admin routes with middleware.
Step 8.1: Import the Middleware Classes
Section titled “Step 8.1: Import the Middleware Classes”Open app/Routes/web-routes.php and add the following imports at the top. AuthController is already imported from Lab 8.
use App\Middleware\AuthMiddleware;use App\Middleware\AdminAuthMiddleware;Step 8.2: Register the Login and Logout Routes
Section titled “Step 8.2: Register the Login and Logout Routes”Add the following routes next to the routes from Lab 8. They do not need middleware: users must be able to submit the login form without being logged in.
// TODO: Create a POST route for '/login' that maps to AuthController::class 'authenticate' method// Set the route name to 'auth.authenticate'
// TODO: Create a POST route for '/logout' that maps to AuthController::class 'logout' method// Set the route name to 'auth.logout'Step 8.3: Protect the User Dashboard
Section titled “Step 8.3: Protect the User Dashboard”This route requires a login and is available to both admins and customers:
$app->get('/dashboard', [AuthController::class, 'dashboard']) ->setName('user.dashboard') ->add(AuthMiddleware::class);->add() attaches the middleware to this route only. It checks the session before dashboard() runs.
Step 8.4: Protect the Admin Routes
Section titled “Step 8.4: Protect the Admin Routes”Find your existing $app->group('/admin', ...) from Lab 3 and add ->add(AdminAuthMiddleware::class) after its closing parenthesis:
$app->group('/admin', function ($group) { $group->get('/dashboard', [AdminDashboardController::class, 'dashboard'])->setName('admin.dashboard'); // ... your other admin routes})->add(AdminAuthMiddleware::class);Adding the middleware to the group applies it to every route in the group, so you do not need to add it to each route.
Routes Created:
| Method | URI | Controller Method | Route Name | Middleware |
|---|---|---|---|---|
| POST | /login | AuthController::authenticate() | auth.authenticate | None |
| POST | /logout | AuthController::logout() | auth.logout | None |
| GET | /dashboard | AuthController::dashboard() | user.dashboard | AuthMiddleware |
| All | /admin/... | Lab 3 to Lab 7 controllers | admin.* and others | AdminAuthMiddleware |
Step 9: Test Your Authentication
Section titled “Step 9: Test Your Authentication”- Valid login: Visit
http://localhost/your-app-name/loginand log in with the customer account from Lab 8. You should be redirected to/dashboardwith a welcome message, and the dashboard should display your name, email, and role. - Login with username: Log out, then log in with your username instead of your email. It should work the same way.
- Invalid credentials: Try a wrong password, then an email that is not registered. Both attempts should display “Invalid credentials.” and keep the identifier in the field, with an empty password field.
- Session ID changes at login: Open the developer tools, select the Application tab (Storage in Firefox), and note the value of the
PHPSESSIDcookie. Log in. The cookie value should be different. - Protected route: Log out, then visit
/dashboard. You should be redirected to the login page with an error message. - Customer on admin route: Log in as the customer and visit
/admin/dashboard. You should be redirected to/dashboardwith “Access denied.” - Admin login: Log out, then log in as the admin account. You should be redirected to
/admin/dashboard, and the admin header should display your name instead of “Admin”. - Logout: Click “Logout” on the user dashboard. You should see “You have been logged out.” on the login page. Visit
/dashboardagain: you should be redirected to login.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
-
verifyCredentials()accepts an email or a username -
SessionManager::regenerate()exists and is called at login and logout - Every login failure displays the same “Invalid credentials.” message
-
AuthMiddleware.phpandAdminAuthMiddleware.phpexist inapp/Middleware/ -
/dashboardrequires a login, and/adminroutes require the admin role - Customers and admins are redirected to different pages after login
- The admin header displays the logged-in user’s name
- Logout is a POST request and displays a success message