Reputation: 25
I can't work out how best to pass user details (email, name, etc.) to 'logged in' views (I'm using jade).
I'm using passport and have access to session.passport.user
in my views but only the user's _id is saved on here, and i've been told it would be bad security practice to persist it locally in the session cookie.
I don't want to have to pass a user object to res.render
on each controller that I need the user.
this is how i have sessions setting up locally
app.use(function (req, res, next) {
res.locals.session = req.session;
next(null, req, res);
});
and this is my middleware to check if a user is logged in
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) {
return next();
}
// if they aren't redirect them to the home page
res.redirect('/');
}
I have looked at dynamic helpers but I'm using express v3.0.0rc4.
Upvotes: 1
Views: 1347
Reputation: 27282
You can use res.locals
for this purpose. Anything you put in that object will be available in the view context (unless, of course, it's overridden by a later context). So, for example, you could modify your isLoggedIn
middleware thusly:
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) {
// obviouisly, don't use static strings...
// get these values from your authentication
// mmechanism
res.locals.user = 'username';
res.locals.userEmail = '[email protected]';
return next();
}
// if they aren't redirect them to the home page
res.redirect('/');
}
Upvotes: 2