req.session.passport为空:req.user undefined

时间:2014-12-04 19:22:51

标签: javascript node.js session cookies express

之前我曾问过类似的问题,但我注意到它出现在Javascript部分。 我现在对于可能出现的问题有更具体的想法。

基本上,req.session.passport在我的日志中是空的。每当我开始在我的网站上导航时,req.user就会变得未定义,因为会话已经没有Passport登录用户了。

我想知道是否有人知道如何解决这个问题?也许这只是Passport配置或整个Express设置中的错误?

App.js:

var express = require("express"),
    bodyParser = require("body-parser"),
    mongodb = require("mongodb"),
    mongoose = require("mongoose"),
    uriUtil = require("mongodb-uri"),
    morgan = require("morgan"),
    session = require("express-session"),
    passport = require("passport"),
    flash = require("connect-flash"),
    ip = "hidden",
    port = process.env.PORT || 80

var app = express()
app.disable("x-powered-by")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))

app.use(morgan("dev")); // log every request to the console

// required for passport
app.use(session({
    secret: "hidden",
    key: 'asdasdasd', 
    cookie: { maxAge: 60000, secure: false },
    resave: true,
    saveUninitialized: false
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

app.set("view engine", "jade")
app.use(express.static(__dirname + "/views"))

require("./includes/passport")(passport)
require("./includes/subject")
require("./includes/user")

Passport.js:

var LocalStrategy = require("passport-local").Strategy,
    User = require("./user"),
    bCrypt = require('bcrypt-nodejs')

module.exports = function(passport) {

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user._id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called "local"

    passport.use('signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : "email",
        passwordField : "password",
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        // asynchronous
        // User.findOne wont fire unless data is sent back
        process.nextTick(function() {

            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ "email" :  email }, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // check to see if theres already a user with that email
                if (user) {
                    return done(null, false, req.flash("message", "Dit e-mail-adres is al bezet"));
                } else {

                    // if there is no user with that email
                    // create the user
                    var newUser = new User();

                    // set the user's local credentials
                    newUser.email = email;
                    newUser.password = createHash(password);
                    newUser.firstname = req.param('firstname');
                    newUser.lastname = req.param('surname');
                    newUser.year = parseInt(req.param('year'));
                    newUser.study = req.param('study');
                    newUser.courses = req.param('courses');
                    newUser.phone = req.param('phone');
                    newUser.availability = req.param('availability');
                    newUser.description = req.param('descText');

                    // save the user
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }

            });    

        });
    }));

    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use("login", new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : "email",
        passwordField : "password",
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) { // callback with email and password from our form

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ "email" :  email }, function(err, user) {

            // if there are any errors, return the error before anything else
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user) {
                console.log('No user found with email ' + email)
                return done(null, false, req.flash('message', 'Gebruiker niet gevonden')); // req.flash is the way to set flashdata using connect-flash
            }

            if (!isValidPassword(user, password)){
                console.log('Incorrect Password');
                return done(null, false, req.flash('message', 'Onjuist wachtwoord')); // redirect back to login page
            }

            // all is well, return successful user
            return done(null, user);
        });

    }));

    var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
    }

    // Generates hash using bCrypt
    var createHash = function(password){
        return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
    }

};

路线:

api.post("/signup", passport.authenticate("signup", {
    successRedirect: "/profile",
    failureRedirect: "/",
    failureFlash: true
}))

api.post("/login", passport.authenticate("login", {
    successRedirect: "/profile",
    failureRedirect: "/login"//,
    failureFlash: true
}))

router.get("/", function(req, res) {
    // serve index.html

    res.render("index", {
        title: 'Home',
        user: req.user,
        message: req.flash("message") 
    })
})

它适用于登录后直接访问的页面,我按如下方式控制:

router.get("/profile", isLoggedIn, function(req, res) {
    res.render("profile", {
        title: 'Gebruikersprofiel van ' + req.user.firstname + " " + req.user.lastname,
        user: req.user // get the user out of session and pass to template
    })
})
function isLoggedIn(req, res, next) {
    console.log(req.session)
    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next()

    // if they aren't redirect them to the home page
    res.redirect("/login")
}

到目前为止,我已经尝试添加中间件来将req.user添加到req.session,并在登录POST中执行相同的操作。此外,我还尝试更改app.js中初始化中间件的顺序。我正在使用新的快速会话版本,没有CookieParser,因为我读到不再需要CookieParser。

如果有人能以任何方式帮助我,我们将不胜感激!我已经被困了一段时间(和其他人一样)。

1 个答案:

答案 0 :(得分:5)

问题不是我在设置会话时遇到的任何问题,或者一般是Passport,而是在我的链接中。 我在某个地方看到有人在多个域中意外工作(他的平台显然是多服务器),这让我今天早上看了我的链接。

显然,我用www链接到我的网站。前缀,但会话初始化没有www。在URL前面。我在饼干里看到了这个。 因此,解决方案是始终如一地通过网站链接,或者使用www。无处不在的地方。