Bibberty
Bibberty

Reputation: 4768

Trying to understand why there are extra brackets at the end of a call

Possibly a silly question, I am trying to work through an example for OAuth and want to understand exactly what is happening before I add to my own code.

Sample is node, express using passport-azure-ad

The route is being defined and a call to passport.authenticate is made.

app.get('/login',
  (req, res, next) => {
      passport.authenticate('azuread-openidconnect', 
      { 
        response: res,
        resourceURL: config.resourceURL,
        failureRedirect: '/' 
      })(req, res, next); // <-- Here is what I am stuck on. 
   },
   (req, res) => {
       log.info('Login was called in the Sample');
       res.redirect('/');
});

I am trying to understand the (req, res, next); that follows directly after the authenticate.

Appreciate any help, or a link to the theory/documentation on this syntax.

Upvotes: 0

Views: 154

Answers (2)

Rami Jarrar
Rami Jarrar

Reputation: 4643

That's because passport.authenticate returns a function (middleware) to handle the request, so you're passing the request to the actual handler here

like this:

function authenticate(someArg) {
    return function (req, res, next) {
        // the handler
    }
}

And this is a simplified version of the example you provided, without the extra explicit pass of the parameters

app.get('/login', passport.authenticate('azuread-openidconnect', { 
    response: res,
    resourceURL: config.resourceURL,
    failureRedirect: '/' 
}), (req, res) => {
    log.info('Login was called in the Sample');
    res.redirect('/');
});

Upvotes: 1

Duncan
Duncan

Reputation: 527

I think this is just a question of understanding the Javascript syntax for what is called a "lambda" function. Consider the following expression:

(a) => { console.log(a) }

That's a way of writing a function that takes one argument and prints it out. You can put that expression in anyplace you need to specify a function that prints out one argument. This is useful because in Javascript functions can be passed around just like data, and this syntax allows you to define a function right when you need it, without bothering to give it a name.

In your example you are calling app.get with three arguments. The first is the string '/login'. The second is a function that takes 3 arguments, and the function is defined right there in line, to call passport.authenticate, which returns a function, which is called with those 3 arguments. The third is a function that takes 2 arguments, also defined right there in line.

Upvotes: 0

Related Questions