Reputation: 23
In Node.js, I used the passportJS LocalStrategy to authenticate the users. And this function
req.getAuthenticated()
Allows me to get whether the current session is authenticated. I also wanted the server to return the username of the current session. To do that, I tried accessing the user property of req.
if(req.isAuthenticated()){
let user = req.user.username;
}
But it is returning 'undefined'. I continued with...
if(req.isAuthenticated()){
console.log(req.user);
}
And it says that the req.user is a 'Promise{ false }', for some reason. I, and then tried out
if(req.isAuthenticated()){
let user = await req.user;
console.log(user);
}
And it returns 'false'. This is the first time I've worked with the passport.js so I may have set it up wrong because req.user should not return a promise, right? Any suggestions?
FOR MORE INFO: Here is what my passport serialization/deserialization and passport.use functions look like:
Again, the getAuthenticated function works perfectly. When users are logged on, they are authenticated, and when they're not, they're not authenticated. I just can't get the req.user properties.
const initialize = (passport, UserCollection, getUserFromUsername, getUserFromId) => {
const authenticateUser = async (username, password, done) => {
let user = await getUserFromUsername(UserCollection, username);
if(user === null){
return done(null, false, {message: 'The user with that username does not exist in the database.'});
}
try{
if(await bcrypt.compare(password, user.password)){
return done(null, user);
}
else{
return done(null, false, {message: 'Passwords do not match'});
}
}
catch {
return done(null, false, {message: 'There was a problem logging you in.'})
}
}
passport.use(new LocalStrategy(authenticateUser));
passport.serializeUser((user, done) => {
return done(null, user._id);
});
passport.deserializeUser((id, done) => {
return done(null, getUserFromId(id));
});
}
Upvotes: 2
Views: 865
Reputation: 22783
You should wait a promise in deserializeUser
:
passport.deserializeUser(async (id, done) => {
const user = await getUserFromId(id);
return done(null, user);
});
Upvotes: 3