CSE 340: Web Backend Development

W05 Learning Activity: Protected Routes

Overview

In this activity, you will learn how to protect routes that should only be available for users who have logged in. You will create middleware that checks if a user is logged in before allowing them to access certain pages. You will also create a dashboard page that displays information for logged-in users.

Preparation Material

In a previous learning activity, you learned how to hide or show links in the user interface based on whether a user is logged in. This same approach could be used to hide a link to an admin page. While this is convenient for the user experience, it is not secure.

Even if a link is hidden on the page, a user can still type the URL directly into the browser address bar. If you do not check on the server whether the user is logged in, they will be able to access pages they should not see. This is a security problem.

Using Middleware to Protect Routes

To solve this problem, you need to create middleware that runs before your route handler functions. This middleware will check if the user is logged in. If the user is not logged in, the middleware will redirect them to the login page. If the user is logged in, the middleware will allow the request to continue to the route handler.

As you have learned previously, middleware functions in Express have access to the request object, the response object, and a function called next(). When you call next(), Express will move on to the next middleware or route handler. If you do not call next(), the request will stop at that middleware.

By adding this middleware to your routes, you can ensure that only logged-in users can access certain pages, even if they try to type the URL directly into the browser.

Activity Instructions

Create Middleware to Protect Routes

In this step, you will create a middleware function that checks if a user is logged in. It can then be used with any route that requires authentication.

Complete the following:

  1. Open your src/controllers/users.js file.
  2. Create a function called requireLogin that does the following:
    • Checks if req.session.user exists.
    • If it does not exist, the function should set an error flash message and redirect the user to the login page.
    • If the user exists on the session, the function should call next() to allow the request to continue.
  3. Export the requireLogin function from the module.
Sample Code (click to expand)
const requireLogin = (req, res, next) => {
    if (!req.session || !req.session.user) {
        req.flash('error', 'You must be logged in to access that page.');
        return res.redirect('/login');
    }
    next();
};

module.exports = {
    // ... other exports
    requireLogin
};

Create a Dashboard Page

You will now create a dashboard page that users can view after they log in. This page will be protected by the middleware you just created.

Complete the following:

  1. Create a new view file called dashboard.ejs in your src/views folder.
  2. In the dashboard.ejs file, create a simple page that displays the user's name and email address. You can assume the name and email address are stored in name and email variables that you will set in your controller (in a future step) and pass them to the view.
  3. Add a heading that says "Dashboard" and a paragraph that displays the user's name and email.
Sample Code (click to expand)
<%- include('partials/header') %>

<main>
    <h1><%= title %></h1>

    <h2>Dashboard</h2>
    <p>Name: <%= name %></p>
    <p>Username: <%= email %></p>

</main>

<%- include('partials/footer') %>

Create a Dashboard Route and Controller

Now you need to create a route and controller function to display the dashboard page. You will use the requireLogin middleware to protect this route.

Complete the following:

  1. Open your src/controllers/users.js file.
  2. Create a new function called showDashboard that does the following:
    • Gets the user's name and email from req.session.user.
    • Renders the dashboard.ejs view and passes the name and email address to it.
  3. Export the showDashboard function.
  4. Open your src/controllers/routes.js file.
  5. Add a new route for /dashboard that uses the requireLogin middleware before calling the showDashboard controller function.
Sample Code (click to expand)
const showDashboard = (req, res) => {
    const user = req.session.user;
    res.render('dashboard', { 
        title: 'Dashboard',
        name: user.name,
        email: user.email
    });
};

Update the Routes File

Now that you have the controller and middleware functions in place, you can update the routes file to use them.

  1. Open your src/controllers/routes.js file.
  2. Import the requireLogin and the showDashboard functions from your users controller.
  3. Add a new GET route for /dashboard that uses the requireLogin middleware before calling the showDashboard controller function as follows:
    // Protected dashboard route
    router.get('/dashboard', requireLogin, showDashboard);

Note on Middleware Order

By placing the requireLogin middleware before the showDashboard controller function in the route definition, you ensure that only authenticated users can access the dashboard page.

Update the Login Controller

After a user successfully logs in, they should be redirected to the dashboard page instead of staying on the login page.

Complete the following:

  1. Open your src/controllers/users.js file.
  2. Find the processLoginForm function that handles the login form submission.
  3. After the user successfully logs in and their information is stored in the session, change the redirect to send them to /dashboard instead of the root home page.

Add a Link to the Dashboard page

At the bottom of your home page (src/views/home.ejs), add a link "My Dashboard" that links to the dashboard page so that logged-in users can easily navigate to it. This link should only be visible if the user is logged in.

Sample Code (click to expand)
<% if (isLoggedIn) { %>
    <p><a href="/dashboard">My Dashboard</a></p>
<% } %>

Test the Protected Route

You should now test that your protected route is working correctly.

Complete the following:

  1. Start your server if it is not already running.
  2. Open your browser and try to go directly to the dashboard page by typing the URL (for example, http://127.0.0.1:3000/dashboard) without logging in first.
  3. You should be redirected to the login page and see an error message.
  4. Now log in with a valid user account.
  5. You should be redirected to the dashboard page and see the user's email displayed.
  6. Try logging out and then accessing the dashboard URL again to confirm that you are redirected to the login page.

Testing Tip

Make sure to test both scenarios: accessing the protected page when you are not logged in, and accessing it when you are logged in. This will help you confirm that your middleware is working correctly.

Next Step

Complete the other Week 05 Learning Activities

After you have completed all the learning activities for this lesson, return to Canvas to submit a quiz.

Other Links: