3

I have a simple nodejs/express application by this example. In that view there is checking everyauth.loggedIn variable, but in my application I don't use everyauth module I use the following code instead:

req.session.auth = user;

How can I get access to req.session.auth in a view in this case?

Erik
  • 14,060
  • 49
  • 132
  • 218
  • 1
    If you landed here and are using Express 3.0, here is the answer: http://stackoverflow.com/questions/11580796/migrating-express-js-2-to-3-specifically-app-dynamichelpers-to-app-locals-use – plus- Jan 16 '13 at 21:32

2 Answers2

7

You'll need to use a dynamicHelper to expose anything in the session object (or the session object itself). You can do something like this in your app.js:

app.dynamicHelpers({
  auth: function(req, res){
    return req.session.auth;
  }
});

Then in your views, you will have an auth variable that points to the session object. For example:

You are logged in as <%= auth.name %>
Scott Arrington
  • 12,325
  • 3
  • 42
  • 54
  • Thank you. Is there in that approach any security issues? – Erik Feb 03 '12 at 19:24
  • It's just a helper method that is exposed to your views, so I can't think of any security concerns. I would generally follow the rule of exposing only what I need, though. – Scott Arrington Feb 03 '12 at 23:24
1

Just to add some information, Scott's answer is the way to go to make the "auth" object available in all your views (Express' Dynamic Helpers doc), but if you only want to use it only in one specific view, you can pass it using the locals in the render method (Express' res.render doc):

res.render('yourView', { auth: req.session.auth });
mna
  • 22,989
  • 6
  • 46
  • 49