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.
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
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)
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.
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.
Next, we'll use the Passport.js middleware to authenticate our users. Passport.js supports multiple strategies like 'local' (username & password) and OAuth.
Lastly, we'll use Express-sessions to maintain the authenticated state across multiple requests/pages.
// 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');
}
});
// 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();
}
});
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)
req.logout()
and req.session.destroy()
connect-flash
modulereq.user
to access the logged-in user's dataRemember to practice regularly to improve your skills. Happy coding!