Passport JS
Introduction
It is authentication middleware for NodeJS which facilitate to separate to the authentication logic into several parts to make the structure more clearer
The authentication logic can mainly be separated into 2 parts - Strategy, Middleware
Strategy
It mainly includes the logic of authentication and store the user into request
const LocalStrategy = require('passport-local').Strategy;
const User = require('./account');
const bcrypt= require('bcryptjs');
// validation logic
const strategy = new LocalStrategy(function (username, password, done) {
let checkusername = `SELECT * FROM account WHERE username=?`
User.query(checkusername, [username], function (err, result) {
if (result.length > 0) {
bcrypt.compare(password, result[0].password, function (err, match) {
if (err) throw err;
if (match) {
// set the user into request
return done(null, result, {message:username});
} else {
// the request user be false when failed to login
return done(null, false, { message: 'Wrong Password'});
}
});
} else {
return done(null, false, {message: 'Wrong Username'});
}
})
})
}
module.exports = strategy;
Middleware
It is used to bind the validation rule defined by strategy previously to the middleware
After that, put it into the route in order to do follow-up action based on the validation result
const express = require('express');
const app = express();
const passport = require('passport');
const session = require('express-session');
const strategy = require("./passport/strategy');
// initialize
app.use(passport.initialize());
// optional, for session only
app.use(session({
secret: 'Mole',
resave: true,
saveUninitialized: true
}));
app.use(passport.session());
// create middleware and map the name with the strategy
passport.use("local", strategy);
// optional, use in session, after finished validation, only store username
// into session when user finished validation
passport.serializeUser(
function (user, done) {
done(null, user[0].username);
});
// optional
// if the session is found for the request, get back user based the id stored in
// session and then set back the result to request.user
passport.deserializeUser(
function (username, done) {
let checkaccount = `SELECT * FROM account WHERE username=?`
User.query(checkaccount, [username], function (err, result) {
done(err, result[0]);
});
});
app.post('/login/password',
// apply middleware to the route
passport.authenticate('local', { failureRedirect: '/login', failureMessage: true }),
// after validation, do the follow up action with the response
function(req, res) {
// user is set to the request
res.redirect('/~' + req.user.username);
});
Documentation
Last updated
Was this helpful?