virattara virattara - 4 months ago 22
Javascript Question

Unable to access req.user in Passport.js on Express.js

req.user
not accessible anywhere except its origin function.

I read that passport attaches the user to every request after authentication.

I want to stop any user from accessing the inner pages through the url bar thus skipping the login page or if his session is already active he must be redirected to the user page. These two things can be done only if I get access to
req.user
in all the middlewares.

app.js link

app.js:-

app.post('/',passport.authenticate('local',{failureRedirect: '/'}),
function(req,res,next){
console.log(req.user); //req.user defined here only not in users.js
res.redirect('/users');
});


users.js:-

router.get('/users', function(req, res, next) {
console.log(req.user);//undefined
res.render('users');
});


DeserializeUser:-

passport.deserializeUser(function(id, done) {
db.findById(id, function(err, user) {
done(err, user);
console.log(user) //undefined
});
});

Answer

It doesn't look like your app is set up to support sessions, which is generally what's needed for Passport to "remember" that a user has logged in, and to populate req.user.

The most common session middleware for Express is express-session, and it relatively easy to set up.

For a quick check, to see if this is the problem, you can add the following to your app:

app.use(session({ secret: 'super secret' }));

Make sure you add it before app.use(passport.session()).

If that works, you should read up on how to configure a session store, and what the various other options of the session middleware are.