Authentication Flow

Tutorial 4 of 4

1. Introduction

1.1 The Tutorial's Goal

This tutorial aims to guide you on how to set up a complete authentication system in your Express.js application. It covers everything from user registration to login, and maintaining authenticated states.

1.2 What You Will Learn

By the end of this tutorial, you will be able to:
- Set up user registration and login forms
- Authenticate users using Express and Passport.js
- Maintain authenticated state across sessions

1.3 Prerequisites

To get the most out of this tutorial, you should have a basic understanding of:
- JavaScript (ES6)
- Node.js & Express.js
- MongoDB (or any other database)

2. Step-by-Step Guide

2.1 User Registration

Firstly, you need to set up the user registration form and save the user data in your database. Make sure to hash the password before storing it to maintain security.

2.2 User Login

Once user registration is complete, you'll set up the login form. Here, you'll need to verify the entered credentials with the ones in the database.

2.3 User Authentication

Next, we'll use the Passport.js middleware to authenticate our users. Passport.js supports multiple strategies like 'local' (username & password) and OAuth.

2.4 Maintaining Authenticated State

Lastly, we'll use Express-sessions to maintain the authenticated state across multiple requests/pages.

3. Code Examples

3.1 User Registration

// Import necessary modules
const express = require('express');
const bcrypt = require('bcrypt');
const User = require('./models/User');

const app = express();

// User Registration Route
app.post('/register', async (req, res) => {
    try {
        // Hash password
        const hashedPassword = await bcrypt.hash(req.body.password, 10);

        // Create user
        const user = new User({
            username: req.body.username,
            password: hashedPassword
        });
        await user.save();

        res.redirect('/login');
    } catch {
        res.redirect('/register');
    }
});

3.2 User Login

// User Login Route
app.post('/login', async (req, res) => {
    // Find user
    const user = await User.findOne({ username: req.body.username });

    if (user == null) {
        return res.status(400).send('Cannot find user');
    }

    // Check password
    try {
        if (await bcrypt.compare(req.body.password, user.password)) {
            res.send('Success');
        } else {
            res.send('Not Allowed');
        }
    } catch {
        res.status(500).send();
    }
});

4. Summary

In this tutorial, we have covered:
- Setting up user registration and login routes
- Using bcrypt to hash passwords
- Using Passport.js for user authentication
- Maintaining authenticated state using Express-sessions

For further learning, you can look into:
- Other Passport.js strategies
- Connect-flash for flash messages
- More secure session stores (like connect-mongo)

5. Practice Exercises

  1. Create a route to logout the user.
  2. Hint: Use req.logout() and req.session.destroy()
  3. Add flash messages for successful registration, login and errors.
  4. Hint: Use the connect-flash module
  5. Implement a route to display the profile page of the logged-in user.
  6. Hint: Use req.user to access the logged-in user's data

Remember to practice regularly to improve your skills. Happy coding!