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

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

问题描述

我在 Sails 中使用模型的 toJSON() 方法,以便在模型通过应用程序的 API 公开时控制其某些属性的可见性.

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.

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

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 在模型中使用会话参数

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

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

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

Sails Google 小组讨论该主题

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

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