Guest User

login

a guest
Dec 9th, 2017
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var LocalStrategy   = require('passport-local').Strategy;
  2. var User = require('../models/user');
  3. var bCrypt = require('bcrypt-nodejs');
  4.  
  5. module.exports = function(passport){
  6.  
  7.     passport.use('login', new LocalStrategy({
  8.             passReqToCallback : true
  9.         },
  10.         function(req, username, password, done) {
  11.             // check in mongo if a user with username exists or not
  12.             User.findOne({ 'username' :  username },
  13.                 function(err, user) {
  14.                     // In case of any error, return using the done method
  15.                     if (err)
  16.                         return done(err);
  17.                     // Username does not exist, log the error and redirect back
  18.                     if (!user){
  19.                         console.log('User Not Found with username '+username);
  20.                         return done(null, false, req.flash('message', 'User Not found.'));                
  21.                     }
  22.                     // User exists but wrong password, log the error
  23.                     if (!isValidPassword(user, password)){
  24.                         console.log('Invalid Password');
  25.                         return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
  26.                     }
  27.                     // User and password both match, return user from done method
  28.                     // which will be treated like success
  29.                     return done(null, user);
  30.                 }
  31.             );
  32.  
  33.         })
  34.     );
  35.  
  36.  
  37.     var isValidPassword = function(user, password){
  38.         return bCrypt.compareSync(password, user.password);
  39.     }
  40.    
  41. }
Add Comment
Please, Sign In to add comment