Home > Software engineering >  Passport.JS deserializeUser Is Never Reached
Passport.JS deserializeUser Is Never Reached

Time:05-21

I have tried almost every method known to stack Overflow but my issue is persisting as the days goes by and I'm really hoping for some help here. As you can tell from the title, Passport-local does not call deserializeUser for some odd reason. My files are set up as shown below.

User.js

const express = require('express');
const app = express();
const router = express.Router();
// const db = require('../config/db');
const session = require('express-session');
const SqlDbStore = require('express-mysql-session')(session);
const passport = require('passport');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const cookieParser = require('cookie-parser')

//----------------------------------------- BEGINNING OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------
app.use(session({
    key: 'session_cookie_name',
    secret: 'session_cookie_secret',
    store: new SqlDbStore({
    host: 'localhost',
    port: 3306,
    user: 'xxxxxxxxxx',
    password: 'xxxxxxxxx',
    database: 'xxxxxxxxxx',
    }),
    resave: false,
    saveUninitialized: false,
    cookie:{
        maxAge:1000*60*60*24,
        secure: false
    }
}));
app.use(passport.initialize());
app.use(passport.session());
require('../config/ppc.js')(passport);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
/*passport middleware*/
function genPassword(password) {
    var salt=crypto.randomBytes(32).toString('hex');
    var genhash=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString('hex');
    return {salt:salt, hash:genhash}
};
function checkAuthentication(req,res,next){
    if(req.isAuthenticated()){
    //req.isAuthenticated() will return true if user is logged in
        next();
    } else{
        res.redirect("/login");
    }
};  
//----------------------------------------- END OF PASSPORT MIDDLEWARE AND SETUP ---------------------------------------------------

router.post('/register', (req, res) => {
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const email = req.body.email;
    const saltHash = genPassword(req.body.password);
    const salt = saltHash.salt;
    const hash = saltHash.hash;

    db.query('SELECT * FROM Users WHERE UsersEmail = ? ', [email], (err, results) => {
        if (err){
            console.log(err)
        } else if (results.length > 0) {
            res.json({ message: 'Email is already registered!' });
        } else {
            db.query('INSERT INTO Users (UsersFirstName, UsersLastName, UsersEmail, UsersPasswordHash, UsersPasswordSalt) VALUES (?, ?, ?, ?, ?)', [firstName, lastName, email, hash, salt], (err, results) => {
                if (err){
                    console.log(err);
                };
                res.send(results);
            });
        }
    })
});

router.post('/login', function(req, res, next){
    // console.log(req.body);
    passport.authenticate('local', function(err, user){
    //   console.log('Error: '   err);
    //   console.log('User ID: '   user.id   '\nUser Email: '   user.email   '\nUser Salt: '   user.salt   '\nUser Hash: '   user.hash);
    //   console.log(err, user);
      if(err) {
        res.json({message: err.message});
      }
      if(!user) {
        res.json({message: info.message});
      }
      req.logIn(user, (err) => {
        if(err) {
          res.json({message: err.message});
        } else {
          return res.redirect('/');
        }
      });
    })(req, res, next);
  });
  module.exports = router;

PPC.js

module.exports = function (passport) {
    const LocalStrategy = require('passport-local').Strategy;
    const db = require('./db');
    const crypto = require('crypto');

    db.connect((err) => {
        if (!err) {
        console.log("BD Connected");
        } else {
        console.log("BD Conection Failed");
        console.log(err.message);
        res.json({message: err.message})
        }
    });
    const customFields={
        usernameField: 'email',
        passwordField:'password',
    };
    /*Passport JS*/
    const verifyCallback=(email,password,done)=>{
        db.query('SELECT * FROM Users WHERE UsersEmail= ?', [email], function(error, results, fields) {
            if (error) {
                console.log('query error: '   error);
                return done(error);
            }

            if(results.length==0) {
            return done(null,false, { loggedIn: false, message: 'Account is not recognized.'});
            }

            const isValid=validPassword(password, results[0].UsersPasswordHash, results[0].UsersPasswordSalt);
            user={id:results[0].UsersID, email:results[0].UsersEmail, hash:results[0].UsersPasswordHash, salt:results[0].UsersPasswordSalt};
            if(isValid) {
                return done(null,user, { loggedIn: true, email: email});
            } else{
                return done(null,false, { loggedIn: false, message: 'Password is incorrect.'});
            }     
        });
    };
    const strategy = new LocalStrategy(customFields, verifyCallback);
    passport.use(strategy);
    passport.serializeUser((user,done)=>{
        console.log('Inside serialize');
        done(null, user.id);
    });
    passport.deserializeUser((userId, done) => {
        console.log('Inside deserialize');
        db.query('SELECT * FROM Users WHERE UsersID = ?', [userId], function(error, results) {
        done(null, results[0]);
        });
    });
    function validPassword(password, hash, salt){    
    const hashVerify=crypto.pbkdf2Sync(password, salt, 10000, 60, 'sha512').toString("hex");
    return hash === hashVerify;
    };    
}

I am totally unsure as to what I did wrong here. One thing I will say is, when I change all app.use() to router.use() in my User.Js, I got a consider upgrading MySQL error when I am using mysql2. Regardless, I don't think mysql is my issue because I am able to register to the DB fine using mysql2 and app.use. I believe my issue most likely lies in the router.post(/login).

CodePudding user response:

I ended up just moving to my own encryption method which uses bcrypt. It was the easiest and securest way to go about this process especially with out wasting to much time. If I ever find the solution in the future, I’ll post it on GitHub and will post the link here.

More information on Bcrypt.

  • Related