Meteor 将 CRUD 操作限制为管理员或文档所有者

Meteor restrict CRUD operations to admins or the document owner

目前在我的流星应用程序中,我希望能够将数据库 CRUD 操作限制为仅文档所有者,或者例如,如果他们具有管理员权限。

我正在使用 meteor alanning:roles 包,有人可以解释一下我如何最好地利用这个包来限制谁可以根据他们的角色创建、阅读或更新文档,或者他们是否是文档?

这个小代码片段是从 http://discovermeteor.com 借来的。它应该对此事有所启发。

 ownsDocument = function(userId, doc) {
      return doc && doc.userId === userId;
 };

 Posts = new Meteor.Collection('posts');

 Posts.allow({  
      update: ownsDocument         
 });

因为我没有使用过角色包,所以我帮不上忙。但快速浏览 github 页面后,它看起来非常简单。

使用 alanning:roles 包,您可以使用 Roles.userIsInRole(userId,role),其中 userId 和角色是一个字符串。

因此您可以执行以下操作。

Posts.allow({
  update:function(){
     var currentUser = Meteor.user(),
         isUserAdmin = Roles.userIsInRole(currentUser,'Admin');
      if(isUserAdmin){
         console.log("Ok the user is logged in on an admin account, lets allow it to update")
         return true;
      }else{
        console.log("Someone just try to update the document and he isn't logged in into an admin account")
        return false;
    }
  }
})

此外,如果您想仔细检查用户是 admin 还是文档的 owner,只需使用 || 或运算符。

if(isUserAdmin || doc.userId === userId){return true;}