Accessing session variables in sailsjs view

戏子无情 提交于 2020-01-23 04:44:49

问题


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.


回答1:


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.




回答2:


for anyone using passport.js, session of the user is saved inside req.session.passport.user and you also can access it directly from the view




回答3:


I have finally decided to go with a solution provided here as I found this to be the neatest solution.

I have created a config file called userdata.config in which I have the following code:

module.exports.userdata = {
    guest: true,
    authenticated: false
};

I am then accessing this in the controller as follows:

sails.config.userdata.authenticated = true;
sails.config.userdata.guest = false;
sails.config.userdata.user = sessionUser;

This is then accessed in the view as follows:

sails.config.userdata.user.firstName


来源:https://stackoverflow.com/questions/21963840/accessing-session-variables-in-sailsjs-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!