Вопрос

I'm experimenting with Passportjs and the code for a Custom Callback is:

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

I'm happy with all of this code except for the second to last line (req, res, next); - Could someone explain why these parameters are added on the end. This is probably more of a JS question than a Passport question but any help is much appreciated.

Это было полезно?

Решение

The "javascript" answer is that it returns a function which is called again with those 2nd set of arguments.

That function is the "accumulator for failures from each strategy in the chain".

https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js

Другие советы

You can rewrite it without the anonymous function, or the custom callback. Just use passport's passport.use(new LocalStrategy()) function to create the new strategy. See 'Configure' docs.

passport.use(new LocalStrategy(
  function(username, password, done) {
    logIn({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

The only change you need to make is move the logIn function to be in this file, and not a method to req. Then you can simply call passport.authenticate like so:

app.get('/login', passport.authenticate('local', { successRedirect: '/',
                                                   failureRedirect: '/login' }));

So instead of using res.redirect in the callback, you just use passport's built in successRedirect and failureRedirect properties. You can see their docs as well, on the authentication page.

Connect/Express middleware function has signature:

function(req, res, next)

passport.authenticate() can be used as a middleware, e.g:

app.post('/login', passport.authenticate('local'), nextMiddleware);

This means authenticate() returns a middleware function object, which you can evoke with (req, res, next) parameters to continue the app's request-response cycle.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top