Intro to Passport Authentication

What is Passport.js?

Let’s Start

Here, we will create application which will do following things only:

Project Structure will be like this:

+ server
 + user(there can be multilple other modules like user)
    + user.server.controller.js
    + user.server.model.js
    + user.server.route.js
 + config
    + config.js
    + db.js
 + routes.js
+ server.js
+ package.json
+ README.md

1. Setting up Server using Express Framework.

πŸ“ You can see code in Code Folder. Here’s the link

First of all, we required all the module dependencies. After that we used middleware instances body-parser, cookie-parser and express-session. We used Mongodb to store database. You can see we loaded db file, so our connection will established, when we will start our server.

2. Setting up Database connection using Mongoose.

const Mongoose = require('mongoose');
const config = require('./config');
Mongoose.connect(config.db);
const db = Mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function callback() {
    console.log("Connection with database succeeded.");
});
exports.db = db;

3. Setting up Passport

/*!
 * Module dependencies.
 */
const User = require('../user/user.server.model').User;
const local = require('./passport/local');
/**
 * Expose
 */
module.exports = function (passport) {
  // serialize sessions
  passport.serializeUser(function(user, done) {
    done(null, user.id)
  })
  passport.deserializeUser(function(id, done) {
    User.findOne({ _id: id }, function (err, user) {
      done(err, user)
    })
  })
  // use these strategies
  passport.use(local);
};

What is passport serializer and deserializer?

πŸ“ You can see code in Code Folder. Here’s the link

Once the load returns with our user object the only thing left is to compare the Unknown User and password to see if there is a match. If it is a match, we let the user in (by returning the user to passport β€” return done(null, user)), if not we return an unauthorized error (by returning nothing to passport β€” return done(null, false, {message: ”})). How route endpoint to use passport authentication.

app.post('/login', passport.authenticate('local', {}), User.login);