【发布时间】:2016-04-10 06:06:26
【问题描述】:
坦率地说,我今天才开始学习护照。我觉得我了解护照的一些工作原理,但我仍在努力熟悉自己。我的问题(我认为)是我的用户被从会话中删除,这阻止了我到达经过身份验证的路由。我在反序列化函数中 console.logged 用户 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('/');
}
非常感谢任何帮助、见解和建议;谢谢!
【问题讨论】:
-
我认为你的问题是如果
req.isAuthenticated(),你需要在isLoggedIn中使用return。现在你先做next(),然后再做res.redirect('/');。并且没有检查数据库并且知道 确定会话已经消失 - 不要做出这样的假设 :) -
是的,我只是想对可能出现的问题提出一个想法......现在已经有一段时间了:/。你说在 isLogged() 函数中放一个 return,但我不需要 next() 来逃避中间件边缘吗?
-
是的,但是调用
next并不会阻止函数继续执行。所以你现在调用bothnextANDres.redirect。在调用 next 后返回 :) 像next(); return;甚至return next(); -
我真的很感激 Andrey,这就是解决方案 :) 。一切终于奏效了!我一直认为 next() 也起到了回报的作用。
标签: node.js express session-cookies passport.js