Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling passport.authenticate in a separate function isn't working

I'm relatively new to Node and Passport and I was experimenting with login forms using OAuth. I had no problems with setting up Passport and it was completely functional.

It only broke down when I started cleaning up the code to separate the routes from the middlewares.

I've included a part of my code before and after the changes.

So, this works:

module.exports = function(app, passport) {
  	app.get('/login', loginIndex)
    
	app.post('/login', passport.authenticate('local-login', {
        successRedirect : '/profile',
        failureRedirect : '/login',
        failureFlash : true
    }))
    
    function loginIndex(req, res) {
	  res.render('login.ejs', {message: req.flash('loginMessage')})
    }
}

But this does not:

module.exports = function(app, passport) {
  app.get('/login', loginIndex)
  app.post('/login', loginAuth)

  function loginIndex(req, res) {
  	res.render('login.ejs', {message: req.flash('loginMessage')});
  }


  function loginAuth(){
  	  passport.authenticate('local-login', {
          successRedirect : '/profile',
          failureRedirect : '/login',
          failureFlash : true
      })	
  }
}

So, the only difference between the two is that I've moved the passport.authenticate() call into the function loginAuth(). I guess it has to do with the internal working of passport.authenticate(), but I'm not sure.

Thanks.

like image 971
Nikhil Saldanha Avatar asked Feb 07 '26 03:02

Nikhil Saldanha


1 Answers

Try this:

 app.post('/login', loginAuth())

...

function loginAuth(){
      return passport.authenticate('local-login', {
          successRedirect : '/profile',
          failureRedirect : '/login',
          failureFlash : true
      })    
  }

In your original code, you are executing passport.authenticate and in the second version you are just passing a function without executing the passport logic.

like image 121
fmsf Avatar answered Feb 09 '26 03:02

fmsf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!