我试图在SailsJS的策略中成功地序列化和反序列化用户。一个例子就是:
userAuth
var passport = require('passport');
module.exports = function (req, res, next) {
// Check for authorization headers
if(req.get('authorization')){
passport.authenticate('basic', { session: false }, function(err, user, info) {
if ((err) || (!user)) {
return res.json(
{'status':0,
'message':'incorrect username or password'}
);
}
req.logIn(user, function(err) {
if (err) res.send(err);
next();
});
})(req, res);
}else{
// If authentication via session, make sure that authorization headers are off
var is_auth = req.isAuthenticated();
if (is_auth) {
// Ensure that session remembers that user is logged in,
// so that views can reference to them
req.session.isAuthenticated = true;
if (req.user.doctor){
req.session.isDoctor = true;
}else{
req.session.isDoctor = false;
}
return next();
}else{ // User is not allowed
req.session.isAuthenticated = false;
res.status(401);
res.view("user/login");
}
}
};
如您所见,console.log
时req.user的反序列化不仅仅为反序列化对象提供了帮助。但是,当我调用它时,我的usercontroller:login似乎没有反序列化req.user。更多信息见下文:
login
process: function(req, res){
passport.authenticate( ['local'] , function(err, user, info) {
if ((err) || (!user)) {
req.session.flash = {
message : "incorrect username or password"
}
return res.redirect('/user/login');
}
req.logIn(user, function(err) {
if (err) res.send(err);
req.session.user = user;
console.log(req.user);
if(req.user.doctor){
return res.redirect('/assessment/index');
}else{
return res.redirect('/user/show/'+req.session.user.id);
}
});
})(req, res);
},
console.log
{ username: 'username',
createdAt: Mon Feb 09 2015 19:59:04 GMT+0800 (SGT),
id: '54d8a108322359745faf0c5b' }
我误解了什么吗?我需要从req.user中检索反序列化的对象,现在看来我唯一的选择是做一个手动User.find(id ..)。任何帮助表示赞赏! (:
答案 0 :(得分:1)
我发现在passport.authenticate
内,有一个对象在它的回调中返回。因此,req.user现在将是由passport.use(new LocalStrategy(..)
的回调创建的返回用户。
为了解决这个问题,我们必须为req.user添加我们想要的属性。现在它看起来像这样:
var returnUser = {
username: user.username,
doctor: user.doctor,
createdAt: user.createdAt,
id: user.id
};
return done(null, returnUser, {
message: 'Logged In Successfully'
});