在Sails中从模型内部获取当前用户 [英] Get current user from inside the model in Sails

查看:92
本文介绍了在Sails中从模型内部获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过应用程序的API公开模型时,我在Sails中使用模型的 toJSON()方法来控制其某些属性的可见性。 / p>

为了确定要显示的属性和要忽略的属性,我需要知道当前用户的权限。那么,如何从模型内部获取当前用户?还是有更好的方法(模式)来解决此问题?



以下是我想要实现的一些示例代码:

  toJSON:function(){

var result = {};

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

//仅向管理员用户公开电子邮件。
if(currentUser.isAdmin()){
result.email = this.email;
}

返回结果;

}


解决方案

您的提问关于阅读模型调用中的会话。目前,帆和水线的建造方式无法做到。



您可以在初始模型调用中使用 select 属性来限制返回的列。由于这将在您的控制器的上下文中,因此您可以访问req对象。



以下是与此主题相关的一堆相关问题。



sails.js在模型中使用会话参数



是否可以在SailsJS的模型中直接访问会话变量



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



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



在此主题的Google小组讨论中成功


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;

}

解决方案

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

这篇关于在Sails中从模型内部获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆