我有一个Node.js + Express应用程序。护照本地策略会使用用户名向api发送请求。我不想在passport.deserializeUser方法中遇到麻烦,因为我不想一直不断地调用数据库。
这是passport.js代码的样子:
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.uuid);
});
passport.deserializeUser(function(id, done) {
//how do I deserialize the user here?
//usually we would call the database with the id and get the user record/object.
//I do not want to keep calling the API again and again.
});
passport.use(
'local-login',
new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
request.post(
{
url: process.env.LOGIN_API,
form: {email: encrypt(email)}
}, (err, httpResponse, body) => {
if (err) {
return done(null, false, {message : {active : true, text : err}});
}
if(httpResponse.statusCode != 200) {
return done(null, false, {message : {active : true, text : 'Error communicating with server.'}});
}
var user = JSON.parse(body);
if(user == null) {
return done(null, false, {message : {active : true, text : 'Incorrect Email or Password'}});
}
if(!bcrypt.compareSync(password, user.password)) {
return done(null, false, {message : {active : true, text : 'Incorrect Email or Password'}});
}
// all is well, return successful user
return done(null, user);
}
);
})
);
};
我要如何反序列化用户?如评论中所述,我不想为每条路线一遍又一遍地调用api。是否将检索到的用户存储在服务器上的某些JSON文件中?安全吗?如果有大量登录用户该怎么办?
谢谢。