Passport JS反序列化错误

时间:2018-02-13 09:44:51

标签: node.js mongoose passport.js passport-local express-session

我在MEAN堆栈上创建了一个REST API。我遇到了PassportJS反序列化功能的问题。似乎它在我的节点应用程序的整个运行上下文中根本没有被调用。所有其他功能都运行良好。过去两天我一直在努力解决这个问题。 :(我检查了与Passport Auth相关的StackOverflow上的所有帖子但没有帮助。以下是我的代码。我错过了什么?

const passport = require('passport');
const mongoose = require('mongoose');
const status = require('http-status');
const LocalStrategy = require('passport-local').Strategy;

module.exports = function(app) {
    var db = mongoose.createConnection('mongodb://localhost/someDbName');
    var User = db.model('User', new mongoose.Schema({id: {type: Number,required: true,index: true}}));

    passport.serializeUser(function(user, done) {done(null, user.id);});

    passport.deserializeUser(function(id, done) {
        User.findOne({id: id }).exec(done);
    });

    passport.use(new LocalStrategy(function(username, password, done) {
        User.findOne({ 'id': username })
            .exec(function (err, user) {
                if (user && password === user.data.password) {
                    return done(null, user);
                }
                return done(null, false, {message: 'Incorrect Username or Password.'});
            });
    }));

    app.use(require('express-session')({ secret: 'some secret' }));
    app.use(passport.initialize());
    app.use(passport.session());  

    app.post('/api/v1/auth/user/login', function(req, res, next) {
        passport.authenticate('local', function(err, user, info) {
            if (err) {
                return next(err);
            }
            if (!user) {
                return res.
                    status(status.UNAUTHORIZED).send();
            }
            req.logIn(user, function(err) {
                if (err) {
                    return res.
                        status(status.INTERNAL_SERVER_ERROR).send();
                }
                return res.
                    status(status.OK).
                    send(req.user); // req.user is set here
            });
        })(req, res, next);
    });

    app.get('/api/v1/user/data', function(req, res){
        // req.user is always turning up to be undefined here
        // even though we have a session object in the req object.
        if (req.user) { 
            return res.
                status(status.ACCEPTED).
                send(req.user);
        }
        return res.status(status.UNAUTHORIZED).send();
    });
}

PS我正在使用Passport v0.4.0 |猫鼬v4.0.3 |快递v4.16.2。 |节点v6.10.0

1 个答案:

答案 0 :(得分:0)

您需要使用doneerr参数致电user

        passport.deserializeUser(function(id, done) {
          User.findById(id, function(err, user) {
           done(err, user);
          });
        });