Alternatives to findOne() callbacks for passport.js with mongoose

I’m trying to set up passport-local as described here: passport-local

However, as you can see, this uses findOne with a callback, which is no longer supported by mongoose.

However, I’m running into difficulties because while I can find a user, it isn’t getting passed back to my authentication route. Here is the code I have now:


User.findOne({ 'local.email' :  email })
        .then((user)=>{
             if (!user){
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

             }
             if (!user.validPassword(password)){
                 return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
             }

            // return user
            req.user= user;
            done(null, user);
                
        })

Hey :wave: @Veye_Roll,

Welcome to the MongoDB Community forums :sparkles:

I modified the code little bit and it worked fine for me:

User.findOne({ 'local.email': email })
  .then((user) => {
    if (!user) {
      return done(null, false, req.flash('loginMessage', 'No user found.'));
    }
    if (!user.validPassword(password)) {
      return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
    }

    // Assign user to req.user
    req.user = user;
    return done(null, user);
  })
  .catch((err) => {
    return done(err);
  });

Let us know if it helps. Otherwise, could you please share the error message you are receiving?

Best,
Kushagra

I am still seeing an error. For example, upon correct username/password login, it tries to redirect to ‘/profile’ and here is the relevant code from routes.js but you can see that the isLoggedIn fails:


// =====================================
// PROFILE SECTION =====================
// =====================================
// we will want this protected so you have to be logged in to visit
// we will use route middleware to verify this (the isLoggedIn function)
app.get('/profile', isLoggedIn, function(req, res) {
    res.render('pages/profile.ejs', {
        user : req.user // get the user out of session and pass to template
    });
});


// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
    console.log("Upon successful login, this should print a user but prints 'undefined'");
    console.log(req.user);
    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated()){
        return next();
    }
    // if they aren't redirect them to the home page
    res.redirect('/');
}

Ah, I think I figured out the problem here. I have been testing locally and the cookies saved by passport.js weren’t working as a result. I changed the passport section as mentioned here and now it works: express-session - npm