2014-12-04 77 views
1

我以前曾問過類似的問題,但我注意到它是在Javascript部分。 我對現在可能會出錯的更具體的想法也是如此。req.session.passport爲空:req.user undefined

基本上,我的日誌中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

你可以檢查,如果[這](http://stackoverflow.com/questions/26109556/req-session-passport-is-empty-deserializeuser-not-called-expressjs-passport)可能是你的問題? – mvuajua 2014-12-05 08:04:19

+0

這不是,儘管它有希望解決我的另一個問題。 – DatBassie 2014-12-05 10:52:51

回答

4

問題不是我在設置會話或一般護照方面做了錯誤,而是在我的鏈接中。 我在某個地方看到有人偶然在多個域中工作(他的平臺顯然是多服務器),這讓我今天早上通過我的鏈接看。

顯然,我用www連接到我的網站。前綴,但會議初始化沒有萬維網的地方。在URL前面。我在餅乾裏看到了這個。 因此,解決方案是一致地鏈接到網站,要麼有www。前綴無處不在。

相關問題