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

Documentation

Last updated

Was this helpful?