Get current user from inside the model in Sails

不羁的心 提交于 2019-12-12 17:31:25

问题


I'm using toJSON() method of my model in Sails in order to control the visibility of some of it's properties, when model is exposed via application's API.

In order to decide which properties to display and which to omit I need to know the permissions of the current user. So, how do I get the current user from inside the model? Or is there a better way (pattern) to solve this problem?

Here's some sample code I want to achieve:

toJSON: function () {

  var result = {};

  result.firstName = this.firstName;
  result.lastName = this.lastName;

  // Exposing emails only to admin users.
  if (currentUser.isAdmin()) {
    result.email = this.email;
  }

  return result;

}

回答1:


Your asking about reading a session inside the model call. Currently the way sails and waterline are built you can not do this.

You can use the select property on your initial model call to restrict the columns returned. Since this would be in the context of your controller you would have access to the req object.

Here are a bunch of related questions / answers on this topic.

sails.js Use session param in model

Is it possible to access a session variable directly in a Model in SailsJS

https://github.com/balderdashy/waterline/issues/556

https://github.com/balderdashy/waterline/pull/787

Sails Google Group Discussion on the topic



来源:https://stackoverflow.com/questions/33145550/get-current-user-from-inside-the-model-in-sails

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