node.jspassport.jssession-cookiespassport-localpassport-local-mongoose

passport.authenticate() is always executing failureRedirect after saving the user information in mongoDB


I'm a beginner to nodejs and tying to apply authentication using passport, passport-local-mongoose. I have a register page where user can enter mail id and password and click on register button. when user makes a post request by clicking on that button, I want to store the mailid and hash(generated using User.register method from lpassport-local-mongoose) in mongoDB. I'm doing that using passportlocal-mongoose and then wanted to authenticate the user if there are no errors in creating the user.

app.post("/register", function(req, res){

    const username = req.body.mailbox;

    User.register({username: username}, req.body.passwordbox, function(err, user){
        if(err){
            console.log(err);
        }
        else{
         passport.authenticate("local", successRedirect: "/secrets", failureRedirect: "/register")(req, res); 
        }
              
    })
    
});


Solution

  • Based on your provided context, you can try this code:

    app.post("/register", function(req,res){ 
      const username = req.body.mailid 
      User.register({username:username}, req.body.password, function(err, user){ 
        if(!err){ 
          passport.authenticate("local")(req, res, function(){
            res.redirect("/secrets");
          });
        } 
        else {
          res.redirect("/register");
        }
      });
    });
    

    following code using the passport.authenticate() method to authenticate the user, and providing a callback function to redirect to the secrets page if authentication is successful. If an error occurs during user creation, we redirect to the registration page.