Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing session variables in sailsjs view

I am quite new to sailsjs and nodejs. I am trying to create an authentication page, wherein once a user is authenticated, I want to set

req.session.user = user.id
req.session.authenticated = true

I then need to access these values within my main layout.ejs file. I have done so by using

res.locals.user = _.clone( req.session.user )

However, I noticed that this clone method has to be called in every function of every controller so as to allow me to be able to access the user from within the views. Is there a better way of accessing session variables in sailsjs globbaly, without having to clone the req.session in every controller. An example of what I am doing can be found here:

http://pastebin.com/HyE2H4Kq

As you can see, I have called the clone method at the beginning of various functions within the controller.

like image 753
kushaldsouza Avatar asked Feb 23 '14 03:02

kushaldsouza


1 Answers

The req object is available in your views by default, unless you overwrite res.locals completely. So you can access a session variable in your view with <%=req.session.user%> (if you're using EJS). You don't have to copy it explicitly into your locals.

like image 171
sgress454 Avatar answered Oct 05 '22 19:10

sgress454