坦率地说,我今天刚开始学习护照。我觉得我了解护照的一些工作原理,但我仍在努力熟悉自己。我的问题是(我认为)我的用户被从会话中删除,这使我无法到达经过身份验证的路由。我console.log在反序列化函数中记录了用户id,以检查它是否存储在会话中,并且它是。。。
//serialize user into the session
passport.serializeUser(function(user,done){
done(null,user.id);
});
//deserialize the user from the session
passport.deserializeUser(function(id,done){
console.log('user id is: ' + id); //works and logs user id
User.findById(id, function(err,user){
done(err,user);
});
});
这是我的路线和护照中间件。。。
app.post('/login', function(req,res,next){
passport.authenticate('local-login', function(err,user,info){
if(err){
console.log("we have an internal error!");
return next(err);
}
if(!user){
return res.send({success:false, message:'failed to login!'});
}else{
req.login(user, function(err){
if(err){
return next(err);
}
return res.send({ success : true, message : 'authentication succeeded' });
});
}
})(req,res,next);
});
//route middleware to make sure that a user is logged in
function isLoggedIn(req,res,next){
//if the user is authenticated in the session, carry on
if(req.isAuthenticated()){
next();
}
//if they are not authenticated in the session, redirect them to the home page
res.redirect('/');
}
非常感谢任何帮助、见解和建议;谢谢
这是因为您总是将用户重定向到isLoggedIn
中间件中的索引页。需要使用退货:
function isLoggedIn(req,res,next){
if(req.isAuthenticated()){
next();
// STOPS further execution of this function and prevents redirecting the user
return;
}
res.redirect('/');
}
请记住,这只是JavaScript-没有任何框架做任何更改-Express、Passport,甚至Promises都是纯JS,它们不会修改虚拟机的工作方式。GL!
p.s。如果出现问题,特别是在开始时,我建议使用if-else
语句。这样你就不会有问题:
if (req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}