Lev Lev - 2 months ago 13
Javascript Question

How does the Passport custom callback work?

I don't understand this example

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);
});


What I see happening here is

app.get('path', function(req, res, next) {/*bunch of code*/})(req, res, next)


How can this work since it is not a reference to a function that is placed behind (req, res, next) ?

Answer

Your simplified example is a little off, probably due to mismatching brackets and such...

If I reduce the "official" passport example for custom callbacks, I get:

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
  })(req, res, next);
});

So my first assumption is that (req, res, next) are being passed to a express-middleware-compliant function returned from passport.authenticate.

If I go poke around the authenticate code on GitHub, around line 81 or so (as of this writing) it looks like that's just what's happening starting with:

return function authenticate(req, res, next) {
    /* lots and lots of lines follow */
}