如何检查用户是否在 Meteor 中具有特定角色

How to check if a user has a specific role in Meteor

我想管理我的 Meteor 应用程序的用户,为此我需要知道他们当前的角色。我有一个仅供管理员用户访问的页面设置,并且该页面订阅了用户集合。

在此页面的模板中,我有以下内容:

{{#each user}}
  <p>
    <a href="/@{{username}}">{{username}}</a>
    {{#if isInRole 'admin'}} Admin{{/if}}
  </p>  
{{/each}}

不幸的是,这给我留下了一个问题,即登录用户(管理员)的角色是 {{#if isInRole 'admin'}} 块中比较的角色。这导致所有用户都具有管理员身份(事实并非如此)。

如何检查 each 块中显示的用户是否具有特定角色?

编辑注意:我正在使用 alanning/meteor-roles 包

数据库中有所有用户的列表,我想查看他们的管理员状态。

您可以像这样创建自己的角色检查函数:

isAdmin = function(){
  var loggedInUser = Meteor.user();
  var result = false;
  if(loggedInUser){
    if (Roles.userIsInRole(loggedInUser, ['Admin'])){
      result = true;
    }
  }
  return result;
};

例如,将其保存在 ./lib/roles.js 中。

您需要安装 alanning:roles 包才能使用它。

对于以后遇到此问题的任何人,我有以下解决方案。

JavaScript:

Template.registerHelper('isUserInRole', function(userId, role) {
  return Roles.userIsInRole(userId, role);
});

模板:

<p>
  Roles: {{#if isUserInRole _id 'webmaster'}}Webmaster {{/if}}
  {{#if isUserInRole _id 'admin'}}Admin {{/if}}
</p>