Skip to main content

PassportJS Authentication in Node.JS

PassportJS Authentication in Node.JS in 48 Small Steps
  1. Install Node.JS
  2. Create an account with MongoDB Atlas
  3. Create Node.JS project
    • npm init
  4. Install dependencies
    • npm install --save express bcryptjs passport ejs express-ejs-layout mongoose connect-flash express-session
  5. Install nodemon to restart server on every save
    • npm install -D nodemon
  6. Add to scripts in package.json the following
    • "scripts":{"start":"node app.js", "dev":"nodemon app.js"}
  7. Create app.js file
  8. Add boiler plate express
    • const express =  require("express");
    • const app = express();
    • const PORT = process.env.PORT || 5000;
    • app.listen(PORT, console.log(`Server started on PORT ${PORT}`));
  9. Run the following in terminal
    • npm run dev
  10. Create folder routes
  11. Create two files inside routes
    1. index.js
    2. users.js
  12. Inside routes/index.js add the following
    • const express = require("express");
    • const router = express.Router();
    • router.get('/', (req, res) => res.send("Welcome"));
    • module.exports = router;
  13. Inside app.js add the following under const app = express();
    • app.use('/', require('./routes/index'));
  14. Open localhost:5000 in browser
  15. Inside routes/users.js add the following
    • const express = require("express");
    • const router = express.Router();
    • router.get('/login', (req, res) => res.send("Login"));
    • router.get('/register', (req, res) => res.send("Register"));
    • module.exports = router;
  16. Inside app.js add the following under const app = express();
    • app.use('/users', require('./routes/users'));
  17. Open localhost:5000/users/login in browser
  18. Open localhost:5000/users/register in browser
  19. Add express in app.js
    • const expressLayouts = require('express-ejs-layouts');
    • const app = express();
    • app.use(expressLayouts);
    • app.set('view engine', 'ejs');
  20. Create folder named views
  21. Add the following files in Views folder
    1. layout.ejs
    2. welcome.ejs
    3. login.ejs
    4. register.ejs
    5. dashboard.ejs
  22. Include boilerplate html in all the ejs files
  23. Import bootstrap css and javascript files in all ejs or create a common head and put it there and include the head in all ejs files.
  24. Change routes/index.js file
    • Instead of res.send('Welcome'); use res.render('welcome');
  25. Change routes/users.js file
    • Instead of res.send('Login'); use res.render('login');
    • Instead of res.send('Register'); use res.render('register');
  26. To connect to mongoDB database using Mongoose add the following to app.js
    • const mongoose = require("mongoose");
    • const db = process.env.MONGOURI;
    • mongoose.connect(db, { newUrlParser: true }).then(() => console.log("MongoDB Connected").catch(err => console.error(err)));
  27. Create folder called Model
  28. Create a file in Model folder and name it User.js
  29. Inside User.js add the following:
    • const mongoose = require('mongoose');
    • const UserSchema = new mongoose.Schema({name: {type: String, required: true}, email: {type: String, required: true}, password: {type: String, required: true}, date: {type: Date, default: Date.now},});
    • const User = mongoose.model('User', UserSchema);
    • module.exports = User;
  30. Add bodyparser below declaring ejs as view engine
    • app.use(express.urlencoded({ extended: false }));
  31. In router/register import bcrypjs
    • const bcrypt = require('bcryptjs');
  32. Add a post router in register
    • router.post('/register', (req, res) => {
    •     const { name, email, password, password2 } = req.body;
    •     let errors = [];
    •     if(!name || !email || !password || !password2) {
    •         errors.push({  msg: "Please fill in all fields" })
    •     }
    •     if(password !== password2) {
    •         errors.push({  msg: "Passwords do not match" })
    •     }
    •     if(password.length < 6) {
    •         errors.push({  msg: "Password should be at least 6 characters long" })
    •     }
    •     if(errors.length > 0) {
    •         res.render('register', { errors, name, email, password, password2 });
    •     } else {
    •         User.findOne({email: email}).then(user => {
    •             if(user) {
    •                 errors.push({msg: 'Email si already registered.'});
    •                 res.render('register', { errors, name, email, password, password2 });
    •             } else {
    •                 const newUser = new User({ name, email, password });
    •                 bcrypt.genSalt(10, (err, salt) => bcrypt.hash(newUser.password, salt, (err, hash) => {
    •                     if(err) throw err;
    •                     newUser.password = hash;
    •                     newUser.save().then(user => {
    •                         req.flash('success_msg', 'You are now registered and can log in!');
    •                         res.redirect('/users/login');
    •                     ).catch(err => console.error(err));
    •                 }));
    •                 newUser.save();
    •                 res.send(newUser);
    •             }
    •         })
    •     }
    • });
  33. Display error in frontend to display if any of the defined error occurs
  34. Include flash and session in app.js
    • const flash = require('connect-flash');
    • const session = require('express-session');
  35. Below defining body parser define Express Session
    • app.user(session({
    •     secret: 'MYsecret',
    •     resave: true,
    •     saveUninitialized: true
    • }));
  36. Below defining Express Session, define Connect Flash
    • app.use(flash());
  37. Below defining flash, define global variables
    • app.use((req, res, next) => {
    •     res.locals.success_msg = req.flash('success_msg');
    •     res.locals.error_msg = req.flash('error_msg');
    •     next();
    • });
  38. Display the success message in frontend using if (success_msg != '') {}
  39. Display the  error message in frontend using if (error_msg != '') {}
  40. Create a file named passport.js
    • const LocalStrategy = require('passport-local').Strategy; 
    • const mongoose = require('mongoose'); 
    • const bcrypt = require('bcryptjs'); // Load User model 
    • const User = require('../models/User'); 
    • module.exports = function(passport) { 
    •     passport.use( new LocalStrategy({ usernameField: 'email' }, (email, password, done) => { // Match user 
    •         User.findOne({ email: email })
    •         .then(user => 
    •             if (!user) { 
    •                 return done(null, false, { message: 'That email is not registered' }); 
    •             } // Match password 
    •             bcrypt.compare(password, user.password, (err, isMatch) => { 
    •                 if (err) throw err; 
    •                 if (isMatch) { 
    •                     return done(null, user); 
    •                 } else { 
    •                     return done(null, false, { message: 'Password incorrect' 
    •                 }); 
    •              } 
    •          }); 
    •       }); 
    •     })
    •   ); 
    •   passport.serializeUser(function(user, done) { 
    •     done(null, user.id); 
    •   }); 
    •   passport.deserializeUser(function(id, done) { 
    •     User.findById(id, function(err, user) { 
    •         done(err, user); 
    •     }); 
    •   }); 
    • };
  41. Import passport in app.js
    1. const passport = require('passport');
    2. require('./passport').(passport);
  42. Inside app.js after Express Session middleware add the following middleware:
    1. app.use(passport.initialize());
    2. app.use(passport.session());
  43. Import password in routes/users.js
    1. const passport = require('passport');
  44. Add the following POST function to routes/users.js
  45. router.post('/login', (req, res, next) => { // Login
    passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/users/login',
    failureFlash: true
    })(req, res, next);
    });

  46. router.get('/logout', (req, res) => { // Logout
    req.logout();
    req.flash('success_msg', 'You are logged out');
    res.redirect('/users/login');
    });
  47. Inside routes/index.js add the following
    • const express = require('express');
    • const router = express.Router();
    • const { ensureAuthenticated, forwardAuthenticated } = require('./auth');

    • // Welcome Page
    • router.get('/', forwardAuthenticated, (req, res) => res.render('welcome'));

    • // Dashboard
    • router.get('/dashboard', ensureAuthenticated, (req, res) =>
    •   res.render('dashboard', {
    •     user: req.user
    •   })
    • );

    • module.exports = router;
  48. Create a file named auth.js
    • module.exports = {
    •   ensureAuthenticated: function(req, res, next) {
    •     if (req.isAuthenticated()) {
    •       return next();
    •     }
    •     req.flash('error_msg', 'Please log in to view that resource');
    •     res.redirect('/users/login');
    •   },
    •   forwardAuthenticated: function(req, res, next) {
    •     if (!req.isAuthenticated()) {
    •       return next();
    •     }
    •     res.redirect('/dashboard');      
    •   }
    • };

Comments

Popular posts from this blog

Python - List - Append, Count, Extend, Index, Insert, Pop, Remove, Reverse, Sort

🐍 Advance List List is widely used and it's functionalities are heavily useful. Append Adds one element at the end of the list. Syntax list1.append(value) Input l1 = [1, 2, 3] l1.append(4) l1 Output [1, 2, 3, 4] append can be used to add any datatype in a list. It can even add list inside list. Caution: Append does not return anything. It just appends the list. Count .count(value) counts the number of occurrences of an element in the list. Syntax list1.count(value) Input l1 = [1, 2, 3, 4, 3] l1.count(3) Output 2 It returns 0 if the value is not found in the list. Extend .count(value) counts the number of occurrences of an element in the list. Syntax list1.extend(list) Input l1 = [1, 2, 3] l1.extend([4, 5]) Output [1, 2, 3, 4, 5] If we use append, entire list will be added to the first list like one element. Extend, i nstead of considering a list as one element, it joins the two lists one after other. Append works in the following way. Input l1 = [1, 2, 3] l1.append([4, 5]) Output...

Difference between .exec() and .execPopulate() in Mongoose?

Here I answer what is the difference between .exec() and .execPopulate() in Mongoose? .exec() is used with a query while .execPopulate() is used with a document Syntax for .exec() is as follows: Model.query() . populate ( 'field' ) . exec () // returns promise . then ( function ( document ) { console . log ( document ); }); Syntax for .execPopulate() is as follows: fetchedDocument . populate ( 'field' ) . execPopulate () // returns promise . then ( function ( document ) { console . log ( document ); }); When working with individual document use .execPopulate(), for model query use .exec(). Both returns a promise. One can do without .exec() or .execPopulate() but then has to pass a callback in populate.

683 K Empty Slots

  Approach #1: Insert Into Sorted Structure [Accepted] Intuition Let's add flowers in the order they bloom. When each flower blooms, we check it's neighbors to see if they can satisfy the condition with the current flower. Algorithm We'll maintain  active , a sorted data structure containing every flower that has currently bloomed. When we add a flower to  active , we should check it's lower and higher neighbors. If some neighbor satisfies the condition, we know the condition occurred first on this day. Complexity Analysis Time Complexity (Java):  O(N \log N) O ( N lo g N ) , where  N N  is the length of  flowers . Every insertion and search is  O(\log N) O ( lo g N ) . Time Complexity (Python):  O(N^2) O ( N 2 ) . As above, except  list.insert  is  O(N) O ( N ) . Space Complexity:  O(N) O ( N ) , the size of  active . Approach #2: Min Queue [Accepted] Intuition For each contiguous block ("window") of  k  po...