Home > Back-end >  How to perform a function before a redirect with passport.authenticate
How to perform a function before a redirect with passport.authenticate

Time:02-14

I am using WebDevSimplifieds version of a login script. So far its working but I am stuck at the moment with a function I would like to to run before it redirects after logging in.

The user is on a login page where he puts in all credentials and if everything is correct, the user will be redirected to index.ejs(html). Before redirecting I would like to run a function which alters a server variable based on what the user put in into a specific field.

This is working, but of course there is no additional function.

app.post(
  '/login', 
  checkNotAuthenticated, 
    passport.authenticate('local', 
      {
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash: true,
      }
    )
)

I would like to have something like that. The console.log command works, but the passport.authenticate not.

app.post(
  '/login', 
  checkNotAuthenticated, (req, res) => {
    console.log("that works");
    passport.authenticate('local', 
      {
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash: true,
      }
    )}
)

CodePudding user response:

passport.authenticate returns a function that has the signature (req, res, next), i.e. a middleware.

Compare the source code:

module.exports = function authenticate(passport, name, options, callback) {
  // ...

  return function authenticate(req, res, next) {
    // ...
  };

  // ...
};

You need to call that function.

app.post(
  '/login', 
  checkNotAuthenticated,
  (req, res, next) => {
    console.log("that works");

    const authFunc = passport.authenticate('local', {
      successRedirect: '/',
      failureRedirect: '/login',
      failureFlash: true,
    });

    authFunc(req, res, next);
  )}
)
  • Related