简体   繁体   中英

passport.js req.user is returning: 'Promise { false }' - How do I get the current sessions' username?

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));
    });
}

You should wait a promise in deserializeUser :

passport.deserializeUser(async (id, done) => {
        const user = await getUserFromId(id);
        return done(null, user);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM