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

Meteor restrict CRUD operations to admins or the document owner

本文关键字:管理员 文档 所有者 CRUD 操作 Meteor      更新时间:2023-09-26

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

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

使用alanning:roles包,可以使用其中userId和role是String的Roles.userIsInRole(userId,role)

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

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;}

这个小代码片段是从http://discovermeteor.com.这件事应该会有一些线索。

 ownsDocument = function(userId, doc) {
      return doc && doc.userId === userId;
 };
 Posts = new Meteor.Collection('posts');
 Posts.allow({  
      update: ownsDocument         
 });

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