无法使用'roles'包向meteor用户添加角色 [英] unable to add roles to user with meteor using 'roles' package

查看:92
本文介绍了无法使用'roles'包向meteor用户添加角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Atmosphere上提供的'roles'包但我无法使用Accounts.onCreateUser(),我可以在github上获取示例。当我注册一个用户时,我想为他们添加一个角色,当我测试角色是否被分配时,它不会捡起它。

I'm trying to use the 'roles' package available on Atmosphere but I can't get it to work with Accounts.onCreateUser(), I can get the example on github. When I register a user, I want to add a role to them, when I test whether the role is assigned, it's not picking it up.

这是我的代码

/server/users.js

/server/users.js

Accounts.onCreateUser(function(options, user){
  var role = ['admin'];
  Roles.addUsersToRoles(user, role);
  return user;
});

/client/page.js

/client/page.js

Template.hello.events({
  'click input': function () {
    var loggedInUser = Meteor.user();
    if (Roles.userIsInRole(loggedInUser, ['admin'])) {
      console.log("Hi Admin!");
    }else{
      console.log("Please Log In");
    }
  }
});


推荐答案

如果查看<中使用的代码code>角色包你将看到他们使用你传入的user / userId来对用户的集合执行查询( here ,从第〜623行开始:

If you look at the code being used in the Roles package you will see that they use your passed in user/userId to perform a query on the user's collection (here, starting at line ~623):

try {
  if (Meteor.isClient) {
    // On client, iterate over each user to fulfill Meteor's
    // 'one update per ID' policy
    _.each(users, function (user) {
      Meteor.users.update({_id: user}, update)
    })
  } else {
    // On the server we can use MongoDB's $in operator for
    // better performance
    Meteor.users.update(
      {_id: {$in: users}},
      update,
      {multi: true})
  }
}

由于<$ c $在将用户对象插入集合之前调用c> onCreateUser on( docs 将返回的文档直接插入Meteor.users集合),角色在执行查询时找不到它。

Since onCreateUser is called before the user object is inserted into the collection (docs: The returned document is inserted directly into the Meteor.users collection), Roles cannot find it when it performs the query.

为了解决此问题,您必须等到用户插入集合。如果您查看角色包,他们的所有示例都会显示此信息。像这里,(第二个例子,添加评论),以及许多其他人:

In order to fix this you must wait until the user is inserted into the collection. If you look at the Roles package all of their examples show this. Like here, (second example, comments added), along with many others:

// insert user and retrieve the id
id = Accounts.createUser({
  email: user.email,
  password: "apple1",
  profile: { name: user.name }
});

// now we can verify that the user was inserted and add permissions
if (user.roles.length > 0) {
  Roles.addUsersToRoles(id, user.roles);
}

希望能够解决您的问题。所以基本上只需插入用户,然后添加权限。

Hope that shines some light on your issue. So basically just insert the user and then add the permissions after.

这篇关于无法使用'roles'包向meteor用户添加角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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