I am setting up a login route in a web app. When I use the passport.authenticate() method directly in the route's code block, passport.authenticate() fills in req.user, as expected.
app.post('/to-do-list/login', passport.authenticate('local', {failureFlash: true, failureRedirect: '/to-do-list/login'}), async(req,res)=>{
console.log(req.user); // Evaluates to an object containing logged-in users details.
res.redirect('/to-do-list/lists');
}
});
But when I put passport.authenticate('local', {failureFlash: true, failureRedirect: '/to-do-list/login'}) into its own middleware, the login process still succeeds, however req.user is not filled in.
Middleware:
const logUserIn = function(req,res,next){
passport.authenticate('local', {failureFlash: true, failureRedirect: '/to-do-list/login'});
console.log(req.user); // Evaluates as undefined.
next();
};
app.post('/to-do-list/login', logUserIn, async(req,res)=>{
console.log(req.user); // Evaluates to undefined.
res.redirect('/to-do-list/lists');
});
My configuration for Passport is as follows:
app.use(passport.initialize());
app.use(passport.session());
passport.use(new PassportLocal({usernameField: 'loginUserEmail', passwordField: 'loginUserPassword'}, User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
I have read through every piece of documentation I can find that is relevant, but can't figure out what's causing the error.
How do I get Passport to fill in req.user when it is run from a separate middleware?
EDIT: I have since discovered that, if I write the middleware as...
const logUserIn = passport.authenticate('local', {failureFlash: true, failureRedirect: '/to-do-list/login'});
...it runs properly. This defies the Express documentation about how to write middleware, so I would still greatly appreciate anyone who can explain why the previous way I was defining the logUserIn middleware won't work.