Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Passportjs Custom Callback

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.

like image 818
tommyd456 Avatar asked May 07 '14 16:05

tommyd456


People also ask

What are Passportjs strategies?

Strategies are responsible for authenticating requests, which they accomplish by implementing an authentication mechanism. Authentication mechanisms define how to encode a credential, such as a password or an assertion from an identity provider (IdP), in a request.

How does Passport js authentication work?

The “Passport JS” library connects with the “expression-session” library, and forms the basic scaffolding to attach the (authenticated) user information to the req. session object. The main Passport JS library deals with already authenticated users, and does not play any part in actually authenticating the users.

Why should I use Passportjs?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.


1 Answers

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.

like image 185
Dyson Lu Avatar answered Sep 30 '22 19:09

Dyson Lu