我目前正在使用Passport编写Express App。由于护照序列化过程,我需要导出整个login.js文件。我想尽量减少查询,我需要在序列化过程中返回对象的sessionId。我尝试访问init.js文件中的userAfterQuery对象,但它似乎总是undefined
。如果我进行login.userAfterQuery
调用,但如果我使用getter函数并将其称为var obj = login.getter()
,则会发生这种情况。我真的不知道如何解决这个问题,帮助将不胜感激。这不应该是关于异步处理,因为Query嵌套在回调中,并且对象在登录中是defined
。问题在于正确导出对象。
这是init.js:
const LocalStrategy = require("passport-local").Strategy;
var login = require("./login");
//var loginNew = new login();
userObjectAfterQuery = login.userAfterQuery;
//var user = req.user;
module.exports = function(passport) {
//passport serialization to support persistent login sessions
passport.serializeUser(function(user,done){
//console.error(login.toString());
//console.error(loginNew);
console.error(userObjectAfterQuery)
console.error(userObjectAfterQuery.username);
console.log('serializing user: "'+ userObjectAfterQuery.username.S + '"');
done(null, userObjectAfterQuery.sessionId.N);
});
passport.deserializeUser(function(id,done){
consle.log('deserializing user: "'+ userObjectAfterQuery.username.S + '"');
done(err,userObjectAfterQuery);
});
//setting up passport for login and signup
login(passport);
}
这是login.js文件:
module.exports = function(passport) {
var userAfterQuery = {};
passport.use("login", new LocalStrategy({
passReqToCallback: true
},
function(req,username,password,done) {
var queryParams = {
TableName: "users",
KeyConditionExpression: "username = :user",
ExpressionAttributeValues: {
//username entered in jade form
":user":{"S":username}
}
};
//querying dynamodb for username
dynamodb.query(queryParams,
function(err,data) {
if(err) {
console.error(err);
return done(err);
}
//if no users with said username in db
if(data.Count < 1) {
console.error('user: "' + username + '" not found in db');
return done(null, false, req.flash("message" , "user not found"));
}
//too many entries (admin's fault)
if(data.Count > 1) {
console.error('error, more than one user with username: "' + username + '" in the db');
console.error("Entries :" + data.Count);
return done(null,false,req.flash("message", "more than version of the username in the db"));
} else {
//only one user exists in db, query for username was successful
var parsedQueryPw = data.Items[0].password.S;
userAfterQuery = data.Items[0];
//checking if entered password is wrong
if(!isValidPassword(parsedQueryPw, password)) {
console.error("invalid password");
return done(null,false,req.flash("message","invalid user-password combination"));
}
//successful login - user and password match
console.log("login successful");
//return user object for serialization
return done(null,data);
// });
}
});
}
));
}