Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PassportJS Custom Authenticate Callback Not Called

Update: The below error was fixed by a commit. I've marked the first answer as 'correct', though the commit was brought to my attention in one of its comments

I was hoping to utilize the custom callback to handle both successes and failures for logins in Passport's authenticate local strategy, but it looks like it's only called on success.

Here is a snippet of what I'm talking about:

passport.use(new LocalStrategy(
    {usernameField: 'email', passwordField: 'password'},
    function(email, password, done) {
        if(canLogin) done(null, user);
        else done({message: "This is an error message" }, false, { message: "Some Info" });
    }
));


app.post('/login', function(req, res, next) {
      passport.authenticate('local', function(err, user, info) {
         // Only called if err is not set
    });

Any idea why this might be the case? I was under the impression the callback would be called so I can handle errors myself.

like image 308
funseiki Avatar asked Nov 26 '13 00:11

funseiki


1 Answers

If you want to propagate an authentication failure (username/password mismatch), you shouldn't generate an error, but set the user to false and pass a reason along:

passport.use(new LocalStrategy(
  {usernameField: 'email', passwordField: 'password'},
  function(email, password, done) {
    if (canLogin)
      done(null, user);
    else 
      done(null, false, { message: 'Invalid login credentials' });
  }
));
...
app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (user === false) {
      // handle login error ...
    } else {
      // handle successful login ...
    }
  })(req, res, next);
});

The err is reserved for exceptions that occur during the authentication process, for instance if you get DB-errors and such. But although the Passport docs suggest that those errors will be passed to the passport.authenticate callback, they don't seem to (which is the reason why it's not working for you).

like image 131
robertklep Avatar answered Oct 15 '22 08:10

robertklep