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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With