Skip to content

Lab 9: Login & Authentication

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:

  1. The user dashboard, available to any logged-in user.
  2. The admin panel from Lab 3, available only to administrators.

A later lab uses the same AuthMiddleware to require a login before checkout.


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.

Before starting this lab, ensure you have:


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:

  1. Open app/Domain/Models/UserModel.php
  2. Add the following method:
app/Domain/Models/UserModel.php
/**
* 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.
}
  1. Implement the method
  2. Save the file

Hints:

  • Use the findByEmail() and findByUsername() methods from Lab 8.
  • password_verify($password, $user['password_hash']) returns true when the password matches the stored hash.
  • Return null for 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:

  1. Open app/Helpers/SessionManager.php
  2. Add the following method after destroy():
app/Helpers/SessionManager.php
/**
* 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();
}
  1. 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:

  1. Open app/Controllers/AuthController.php
  2. Add the following import at the top:
use App\Helpers\SessionManager;
  1. Replace the login() method from Lab 8 with the following version, and add the authenticate() and logout() methods:
app/Controllers/AuthController.php
/**
* 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.
}
  1. Implement every method marked // TODO
  2. Save the file

Session Keys:

authenticate() stores the following keys. The middleware, the dashboard, and the admin panel read these exact names.

KeyValue
user_id$user['id']
user_email$user['email']
user_nameThe first and last name, separated by a space
user_role$user['role'] ('admin' or 'customer')
is_authenticatedtrue

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.

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:

  1. Navigate to your app/Middleware/ directory
  2. Create a new file named AuthMiddleware.php
  3. Start from the following class structure:
app/Middleware/AuthMiddleware.php
<?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);
}
}
  1. Implement the process() method
  2. 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.


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:

  1. Inside app/Middleware/, create a file named AdminAuthMiddleware.php
  2. Start from the following class structure:
app/Middleware/AdminAuthMiddleware.php
<?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).
}
}
  1. Implement the process() method
  2. Save the file

Objective: Create a page that displays the logged-in user’s information.

Instructions:

  1. Navigate to your app/Views/ directory and create a user/ folder
  2. Inside app/Views/user/, create a file named dashboard.php
  3. Copy and paste the following code:
app/Views/user/dashboard.php
<?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(); ?>
  1. Save the file
  2. Add the following method to AuthController.php:
app/Controllers/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'
}
  1. 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.


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:

  1. Open app/Controllers/AdminDashboardController.php
  2. In the dashboard() method, replace $_SESSION['username'] ?? 'Admin' with SessionManager::get('user_name', 'Admin')
  3. Add use App\Helpers\SessionManager; at the top of the file
  4. Make the same two changes in the index() method of app/Controllers/FlashDemoController.php
  5. Save both files

Objective: Add the login, logout, and dashboard routes, and protect the dashboard and admin routes with middleware.

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.

app/Routes/web-routes.php
// 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'

This route requires a login and is available to both admins and customers:

app/Routes/web-routes.php
$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.


Find your existing $app->group('/admin', ...) from Lab 3 and add ->add(AdminAuthMiddleware::class) after its closing parenthesis:

app/Routes/web-routes.php
$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:

MethodURIController MethodRoute NameMiddleware
POST/loginAuthController::authenticate()auth.authenticateNone
POST/logoutAuthController::logout()auth.logoutNone
GET/dashboardAuthController::dashboard()user.dashboardAuthMiddleware
All/admin/...Lab 3 to Lab 7 controllersadmin.* and othersAdminAuthMiddleware

  1. Valid login: Visit http://localhost/your-app-name/login and log in with the customer account from Lab 8. You should be redirected to /dashboard with a welcome message, and the dashboard should display your name, email, and role.
  2. Login with username: Log out, then log in with your username instead of your email. It should work the same way.
  3. 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.
  4. Session ID changes at login: Open the developer tools, select the Application tab (Storage in Firefox), and note the value of the PHPSESSID cookie. Log in. The cookie value should be different.
  5. Protected route: Log out, then visit /dashboard. You should be redirected to the login page with an error message.
  6. Customer on admin route: Log in as the customer and visit /admin/dashboard. You should be redirected to /dashboard with “Access denied.”
  7. 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”.
  8. Logout: Click “Logout” on the user dashboard. You should see “You have been logged out.” on the login page. Visit /dashboard again: you should be redirected to login.

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.php and AdminAuthMiddleware.php exist in app/Middleware/
  • /dashboard requires a login, and /admin routes 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