DEV Community

Muhammad Awais
Muhammad Awais

Posted on

Passport - Authentication using NodeJS, Express and MongoDB

Install passport, passport-local, passport-local-mongoose Modules

npm install passport@0.4.0 passport-local@1.0.0 passport-local-mongoose@5.0.1 --save
Enter fullscreen mode Exit fullscreen mode

Create a Module name user.js module:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var passportLocalMongoose = require('passport-local-mongoose');

var User = new Schema({
    admin:   {
        type: Boolean,
        default: false
    }
});

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', User);
Enter fullscreen mode Exit fullscreen mode

Add an authenticate.js file on project root directory to authenticate Local to User Model:

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./models/user');

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Enter fullscreen mode Exit fullscreen mode

under /routes folder your users.js looks something like this

var express = require('express');
var router = express.Router();
var passport = require('passport');

const bodyParser = require('body-parser');
var User = require('../models/user');

router.use(bodyParser.json());

router.post('/signup', (req, res, next) => {
  User.register(new User({username: req.body.username}), 
    req.body.password, (err, user) => {
    if(err) {
      res.statusCode = 500;
      res.setHeader('Content-Type', 'application/json');
      res.json({err: err});
    }
    else {
      passport.authenticate('local')(req, res, () => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json({success: true, status: 'Registration Successful!'});
      });
    }
  });
});

router.post('/login', passport.authenticate('local'), (req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.json({success: true, status: 'You are successfully logged in!'});
});

router.get('/logout', (req, res) => {
  if (req.session) {
    req.session.destroy();
    res.clearCookie('session-id');
    res.redirect('/');
  }
  else {
    var err = new Error('You are not logged in!');
    err.status = 403;
    next(err);
  }
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Add following lines to app.js

var passport = require('passport');
var authenticate = require('./authenticate');
...
app.use(passport.initialize());
app.use(passport.session());

app.use('/', indexRouter);
app.use('/users', usersRouter);

// Basic Authentication for session and cookies
function auth (req, res, next) {
  console.log(req.user);

  if (!req.user) {
    var err = new Error('You are not authenticated!');
    err.status = 403;
    next(err);
  }
  else {
    next();
  }
}
app.use(auth);
...
app.use(express.static(path.join(__dirname, 'public')));
Enter fullscreen mode Exit fullscreen mode

Using Postman hit the server

// signup
http://localhost:3000/users/signup
{
    "username": "admin",
    "password": "admin123"
}

// Login
http://localhost:3000/users/login
{
    "username": "admin",
    "password": "admin123"
}
Enter fullscreen mode Exit fullscreen mode

That's all Folks!

Top comments (5)

Collapse
 
jakeerc profile image
Jakeer

ASalamalaikum
Jazakallah khair

Collapse
 
muhammadawaisshaikh profile image
Muhammad Awais

thanks.

Collapse
 
alhassanv profile image
Alhassan

Hey.. I'm not sure this code will work since in your user model you only have admin variable.

Collapse
 
wizsebastian profile image
WizSebastian

RT. He used user.authentication, and his never write authentication function

Collapse
 
feruz00 profile image
Feruz00

Can you write this code with react?
please see this blog: dev.to/feruz00/mern-simple-authent...