you can add authentication, session, and cookie functionality to your application using middleware such as express-session
, passport
, and cookie-parser
.
Here’s an example of a simple ExpressJS application that allows the user to add and view a list of cars stored in a SQLite database and requires the user to log in to view the list of cars. The user’s authentication state is stored in a session using express-session
and their authentication credentials are stored in a cookie using cookie-parser
. Passport is used for authentication:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
const express = require('express') const bodyParser = require('body-parser') const Sequelize = require('sequelize') const session = require('express-session') const passport = require('passport') const LocalStrategy = require('passport-local').Strategy const cookieParser = require('cookie-parser') const app = express() app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use(session({ secret: 'secret key', resave: false, saveUninitialized: false })) app.use(passport.initialize()) app.use(passport.session()) passport.use(new LocalStrategy( async (username, password, done) => { const user = await User.findOne({ where: { username: username } }) if (!user) { return done(null, false, { message: 'Incorrect username.' }) } if (user.password !== password) { return done(null, false, { message: 'Incorrect password.' }) } return done(null, user) } )) passport.serializeUser((user, done) => { done(null, user.id) }) passport.deserializeUser(async (id, done) => { const user = await User.findByPk(id) done(null, user) }) const sequelize = new Sequelize('sqlite::memory:') const User = sequelize.define('user', { username: { type: Sequelize.STRING, allowNull: false }, password: { type: Sequelize.STRING, allowNull: false } }) const Car = sequelize.define('car', { make: { type: Sequelize.STRING, allowNull: false }, model: { type: Sequelize.STRING, allowNull: false } }) app.get('/cars', authenticationMiddleware(), async (req, res) => { const cars = await Car.findAll() res.render('cars', { cars: cars }) }) app.post('/cars', authenticationMiddleware(), async (req, res) => { await Car.create({ make: req.body.make, model: req.body.model }) res.redirect('/cars') }) app.get('/login', (req, res) => { res.render('login') }) app.post('/login', passport.authenticate('local', { |
Above code step by step breakdown
- Required packages and modules: The first section of the code requires the necessary packages and modules, including
express
,body-parser
,sequelize
for SQLite database,express-session
for session management,passport
for authentication,passport-local
for local strategy authentication, andcookie-parser
for handling cookies. - Middleware: The middleware section of the code sets up the application to use
body-parser
,cookie-parser
, andexpress-session
middleware. The session middleware is given a secret key to secure the session, and the passport middleware is initialized and used for the session. - Passport Configuration: In this section, Passport is configured to use the local strategy authentication using the
LocalStrategy
class. TheLocalStrategy
constructor takes a callback function that checks the username and password provided by the user against the database. If the user is found and the password matches, the user is considered authenticated, and the user’s data is stored in the session. - Serialization and Deserialization: The
serializeUser
anddeserializeUser
functions are used by Passport to manage the user’s data stored in the session. TheserializeUser
function stores the user’sid
in the session, and thedeserializeUser
function retrieves the user’s data from the database using theid
stored in the session. - Database: A SQLite database is set up using the
Sequelize
module. Two models are defined,User
andCar
. TheUser
model contains theusername
andpassword
fields, and theCar
model contains themake
andmodel
fields. - Routing: The application defines several routes for adding and viewing cars, and for logging in. The
/cars
route requires the user to be authenticated and displays the list of cars stored in the database. The/login
route displays the login form. The/login
route also handles the post request from the login form and uses thepassport.authenticate
function to check the user’s authentication credentials and start the authentication process. If the user is authenticated, the user’s data is stored in the session, and the user is redirected to the/cars
route. - Authentication Middleware: The
authenticationMiddleware
function is used to check if the user is authenticated. If the user is not authenticated, the user is redirected to the/login
route. This function is used to secure the/cars
route and to ensure that only authenticated users can access the list of cars.
This example is just a basic implementation to demonstrate how to add authentication, session, and cookie functionality to an ExpressJS application using middleware. In a real-world application, you would want to add more security measures, such as hashing passwords, and use a more secure database such as MySQL or PostgreSQL.