Passport.JS 从未达到 deserializeUser

Passport.JS deserializeUser Is Never Reached

我已经尝试了几乎所有已知的堆栈溢出方法,但随着时间的推移,我的问题仍然存在,我真的希望在这里得到一些帮助。从标题中可以看出,Passport-local 出于某种奇怪的原因没有调用 deserializeUser。我的文件设置如下所示。

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;
    };    
}

我完全不确定我在这里做错了什么。我要说的一件事是,当我将 User.Js 中的所有 app.use() 更改为 router.use() 时,我在使用 mysql2。无论如何,我认为 mysql 不是我的问题,因为我可以使用 mysql2 和 app.use 很好地注册到数据库。我相信我的问题很可能出在 router.post(/login).

我最终只是转向了我自己的使用 bcrypt 的加密方法。这是完成此过程的最简单和最安全的方法,尤其是不会浪费太多时间。如果我将来找到解决方案,我会 post 在 GitHub 上 post 并会 link 在这里。

More information on Bcrypt.