【问题标题】:Meteor restrict CRUD operations to admins or the document ownerMeteor 将 CRUD 操作限制为管理员或文档所有者
【发布时间】:2015-05-29 22:49:21
【问题描述】:
目前在我的流星应用程序中,我希望能够将数据库 CRUD 操作限制为仅文档所有者,或者例如,如果他们具有管理员权限。
我正在使用 meteor alanning:roles 包,有人可以解释一下我如何最好地利用这个包来限制谁可以根据他们的角色创建、阅读或更新文档,或者他们是否是文档的所有者?
【问题讨论】:
标签:
javascript
mongodb
security
meteor
permissions
【解决方案1】:
使用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;}
【解决方案2】:
这个小代码 sn-p 是从http://discovermeteor.com 借来的。它应该对此事有所启发。
ownsDocument = function(userId, doc) {
return doc && doc.userId === userId;
};
Posts = new Meteor.Collection('posts');
Posts.allow({
update: ownsDocument
});
因为我没有使用角色包,所以我无能为力。但在 github 页面上快速浏览后,它看起来非常简单。