在重定向后,passport.js会话丢失了

时间:2017-07-17 19:38:42

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

我正在尝试将passport集成到我的node.js应用中。

app.js档案

const app = express();
app.set('view engine', 'pug');
app.use('/libs', express.static('node_modules'));

require('../config/auth.config')(app, data, passport);
app.use((req, res, next) => {
    res.locals.user = req.user;
    next();
});

app.get('/', (req, res) => {
        // those objects are populated correctly after redirect from auth middleware
        console.log(req.session)
        console.log(req.user)
        return res.render('home');
    });
app.get('/login', console.log(req.user);
        // req.user is undefined here
        if (req.user) {
            return res.redirect('/');
        }

        return res.render('login'););
app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login',
}));

auth.config.js

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const LocalStrategy = require('passport-local');
const MongoStore = require('connect-mongo')(session);
const config = require('./config');

const configAuth = (app, {
    users
}, passport, db) => {
    app.use(cookieParser('Purple Unicorn'));
    app.use(bodyParser.urlencoded({
        extended: true,
    }));
    app.use(bodyParser.json());
    app.use(session({
        store: new MongoStore({
            url: config.connectionString
        }),
        secret: 'Purple Unicorn',
        resave: true,
        saveUninitialized: true,
    }));
    app.use(passport.initialize());
    app.use(passport.session());

    passport.use(new LocalStrategy((username, password, done) => {
        return users.login(username, password)
            .then((user) => {
                if (user) {
                    return done(null, user);
                }
                return done(null, false);
            });
    }));

    passport.serializeUser((user, done) => {
        done(null, user._id);
    });

    passport.deserializeUser((id, done) => {
        users.getUserById(id)
            .then((user) => {
                console.log(user);
                if (user) {
                    done(null, user);
                }

                done(null, false);
            });
    });

    app.use((req, res, next) => {
        res.locals = {
            user: req.user,
        };
        next();
    });
};

module.exports = configAuth;

数据对象正常运行。

/login上有正确数据的帖子请求后,我被重定向到/,其中console.log(req.user)打印了正确的用户。它也添加在req.session对象中。

在我关注/login的链接后,它会在检查req.user后重定向我,但会返回undefined。 mongo中的会话正确存储。

护照似乎没有正确保存会话。

1 个答案:

答案 0 :(得分:0)

问题在于deserializeUser方法中,您总是运行done两次回调。在if语句中,你应该使用return done(null, user);从函数中退出;