Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs and PassportJs: Redirect middleware after passport.authenticate not being called if authentication fails

I have no login page but rather I have a login form that appears on every page. I want to redirect user back to the same page they were on regardless of whether authentication was successful (with appropriate flash messages)

Take the following code:

app.post('/login', validateLogin, passport.authenticate('local-login'), function(req, res) {

    var redirectUrl = '/'; 

    if(req.body.to.length > 0){
        redirectUrl = req.body.to;  
    }

    console.log("THIS IS ONLY CALLED IF passport.authenticate() IS SUCCESSFUL");
    res.redirect(redirectUrl);
});

I only see the final middleware above being called if authentication is passed. If it fails then passport appears to be redirecting me to /login in the form of a get request. In my app this page doesn't exist.

If I pass an additional options object as a parameter in the passport authenticate function then this works:

app.post('/login', validateLogin, passport.authenticate('local-login', {

successRedirect : '/', // redirect to the secure profile section
    failureRedirect : '/signup', // redirect back to the signup page. THIS IS JUST FOR TESTING TO SEE IF THE REDIRECT ON FAIL WORKS.
    failureFlash : true, // allow flash messages

}


));

But in doing this I lose the ability to choose where to redirect the user to. It seems that passport takes control over where the user is redirected to if authentication fails. How can I fix this? Or is it a bug? Must passport authenticate be the last middleware in the chain if authentication fails?

This is my local strategy function call:

//LOCAL LOGIN

passport.use('local-login', new LocalStrategy({ 
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form


    console.log("IN PASSPORT");

   if(email.length == 0 || password.length == 0){

       console.log("FIELDS ARE EMPTY"); 
      return done(null, false, req.flash('loginMessage', 'Fill in all values.'));

   }

    // find a user whose email is the same as the forms email
    // we are checking to see if the user trying to login already exists
    User.findOne({ 'local.email' :  email }, function(err, user) {
        // if there are any errors, return the error before anything else



        if (err){
            return done(err);
        console.log("db err");
        }
        // if no user is found, return the message
        if (!user){
            console.log("not user");
            return done(null, false, req.flash('loginMessage', 'Incorrect details.')); // req.flash is the way to set flashdata using connect-flash
        }    
        // if the user is found but the password is wrong

        if (!user.validPassword(password)){
            console.log("invalid pw");
            return done(null, false, req.flash('loginMessage', 'Incorrect details.')); // create the loginMessage and save it to session as flashdata
        }    
        // all is well, return successful user
        console.log("All OK");
        return done(null, user);
    });

}));
like image 459
Paulie Avatar asked Apr 04 '14 09:04

Paulie


Video Answer


2 Answers

You could use a custom authentication callback as described in the last paragraph there http://passportjs.org/guide/authenticate/.

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    // Redirect if it fails
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      // Redirect if it succeeds
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});
like image 86
ploutch Avatar answered Nov 15 '22 22:11

ploutch


I was running into the same issue where the redirect-calls , that follow successful Facebook Auth

  • passport.authenticate('facebook', ..)

.. were not being honored.

Based on 'local' passportJS Strategy - and a nice reminder of that from @ploutch's answer here .. I realized the key to getting it to work seems to be in this call:

req.logIn(user, function(err) {
 ...
}

For Facebook, this route setup worked for me:

app.get(
        '/auth/facebook/callback',

        passport.authenticate
        (
            'facebook', 
            { failureRedirect: '/fbFailed' }
        ),

        function(req, res) 
        {
            var user = myGetUserFunc(); // Get user object from DB or etc

            req.logIn(user, function(err) {

              if (err) { 
                req.flash('error', 'SOMETHING BAD HAPPEND');
                return res.redirect('/login');
              }

              req.session.user = user;

              // Redirect if it succeeds
              req.flash('success', 'Fb Auth successful');
              return res.redirect('/user/home');
            });      
        }
); 
like image 38
Gene Bo Avatar answered Nov 15 '22 21:11

Gene Bo