2

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;

}
Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202

1 Answers1

2

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

Community
  • 1
  • 1
Meeker
  • 5,979
  • 2
  • 20
  • 38
  • Thank you @Meeker, now I see the point. We can't use global object for this, because of concurrent nature of Node.js. However, could you recommend an elegant way to solve my problem? Somehow we will need to inject the current user along the lines... – Slava Fomin II Oct 15 '15 at 20:51
  • Right now, I've extracted all the code to a special serialization service and I call it from inside the toJSON model function. This service requires current user to operate, how do I inject it? Or maybe I need to approach this problem from some other angle where access to request object can be more easily obtained? – Slava Fomin II Oct 15 '15 at 20:54
  • updated my answer with a suggestion about using the select property. – Meeker Oct 15 '15 at 21:02
  • Thank you for a suggestion, however sometimes entities are resolved via `populate` and I want to keep this logic with the model in order to centralize it somehow (entity could be fetched from several places, etc). – Slava Fomin II Oct 15 '15 at 21:07
  • I've managed to solve this problem, just passing the special request context object from controller to the custom serialization function of my models. – Slava Fomin II Oct 16 '15 at 13:27