Can you authenticate with Passport without redirecting?

Hyra picture Hyra · Nov 11, 2014 · Viewed 12.8k times · Source

I have the following working code to authenticate through the passport-local strategy:

  app.post('/api/login', passport.authenticate('local-login', {
    successRedirect : '/api/login/success',
    failureRedirect : '/api/login/error',
    failureFlash : true
  }));
  app.get('/api/login/error', function(req, res) {
    res.send(401, {error: req.flash('loginMessage')});
  });
  app.get('/api/login/success', function(req, res) {
    res.send(200, {user: req.user});
  });

However, ideally I want to handle the errors and success messages from one express route, and not redirect to two extra routes.

Is this possible? I tried using a 'custom callback' but that seemed to error out on serializing users for some reason.

Answer

magmel picture magmel · Nov 11, 2014

You can use custom callback, such as:

passport.authenticate('local', function (err, account) {
    req.logIn(account, function() {
        res.status(err ? 500 : 200).send(err ? err : account);
    });
})(this.req, this.res, this.next);

In err object you can find all needed errors, which was appeared at authentication.