1
我在使用passportJS加載會話時遇到問題。不知何故,每次遇到新的會話請求。 SerializeUser函數無法找到現有會話並最終每次創建一個新會話。現在我怎麼知道這一點?
1.在mongodb中的mysessions
表。對於每個請求,表中都創建了兩個條目。看起來像這樣。PassportJS:會話不按預期工作
{
"_id" : "U_MhBL17rMVdFbuXt7Y5RGjZeHR5mP7O",
"session" : {
"cookie" : {
"originalMaxAge" : 2419200000,
"expires" : ISODate("2016-06-14T14:32:30.721Z"),
"secure" : null,
"httpOnly" : true,
"domain" : null,
"path" : "/"
},
"passport" : {
}
},
"expires" : ISODate("2016-06-14T14:32:30.721Z")
}
{
"_id" : "fSfITl6hGLdvny1PVZ3iJ6_dFzTmNJj3",
"session" : {
"cookie" : {
"originalMaxAge" : 2419200000,
"expires" : ISODate("2016-06-14T14:32:30.808Z"),
"secure" : null,
"httpOnly" : true,
"domain" : null,
"path" : "/"
},
"passport" : {
"user" : "573b11e32147fec27aa9534e"
}
},
"expires" : ISODate("2016-06-14T14:32:30.808Z")
}
這裏是我的environment.js文件
var MongoDBStore = require('connect-mongodb-session')(session);
var sessionStore = new MongoDBStore({
uri: "mongodb://localhost:27017/metaiotAdmin", // Development mode
collection: 'mysessions'
});
sessionStore.on('error', function(error) {
assert.ifError(error);
assert.ok(false);
});
/*session options to be given to express. It's really express keeping the sessions and not passport*/
var sessionOpts = {
saveUninitialized: true,
resave: false,
store: sessionStore,
secret: "cat at my keyboard",
cookie: {
httpOnly: true,
maxAge: 2419200000
}
};
/*declaring all my global variables and dependencies*/
app.use(cookieParser("cat at my keyboard")); // Secret should be kept in a config file and the folder should be added in gitignore
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.text({
type: "text/plain"
}));
app.use(session(sessionOpts));
app.use(passport.initialize());
app.use(passport.session());
我login.js
passport.serializeUser(function(user, done) {
console.log("Serialize", user.id);
done(null, user.id);
});
passport.deserializeUser(function(_id, done) {
console.log("deserializeUser");
Users.findById(_id, function(err, user) {
console.log(err);
done(err, user);
});
});
passport.use('local-login', new LocalStrategy({
passReqToCallback: true
}, function(req, username, password, done) {
Users.findOne({
'emailId': username
}, function(err, user) {
if (err)
return done(err);
if (!user) {
return done(null, false, {
message: 'Username does not exist'
});
} else if (password === user.password) {
console.log("User is verified");
req.session.save();
return done(null, user);
} else
return done(null, false, {
message: "Password does not match"
});
});
}));
app.post('/auth/login', passport.authenticate('local-login'), function(req, res, next) {
res.sendStatus(200);
});
我看不出什麼可怕的錯誤。幫助表示讚賞。