Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform a function before a redirect with passport.authenticate

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
  )}
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading