如何在Firestore中为用户组设置规则

时间:2019-04-07 21:00:20

标签: firebase google-cloud-firestore firebase-security-rules

我是Firestore的新手,我尝试从一组用户那里获取所有资源。 就我而言,我使用auth令牌来跟踪用户组(我也会在云存储上使用它)。

组对象类似于:

{"managers": { "user1_ID": "owner", "user2_ID": "client" } }

然后使用身份验证令牌设置组UID:

{ "groups": { "group1_ID": "owner", "group2_ID": "client" } }

然后在Firestore规则中,我要设置以下内容:

 match /groups/{groupId} {        
   allow create: if request.auth.uid != null;
   allow read: request.auth.token[groupId] != null;
   allow delete, update: if request.auth.token[groupId] == 'owner';
 }

但是,当我有了组ID且读取文档的规则不允许我找到用户所在的所有组时,现在我可以获取或更新文档。

我尝试运行的代码是:

this.unsubscribe = db.collection("groups").onSnapshot(querySnapshot => {
   var groups = [];
   querySnapshot.forEach(function(doc) {
      groups.push({uid: doc.id, ...doc.data()});
   });
   this.setState({sites})
})

我认为(但尚未测试)的唯一解决方案是从auth令牌中获取每个组并请求每个组,但是我认为这可能不是一个好方法。

我已经使用Firestore资源对象名称和ID(甚至将ID插入文档中)进行了测试。

1 个答案:

答案 0 :(得分:0)

最后我明白了。 对于谁正在尝试这种方法,这是我的代码。

规则:

match /groups/{groupId} {        
  allow create: if request.auth.uid != null;
  allow read: if resource.data.managers[request.auth.uid] != null;
  allow delete, update: if resource.data.managers[request.auth.uid] == "owner";
}

客户端JS:

this.unsubscribe = db.collection("groups").where(`managers.${firebase.auth().currentUser.uid}`, ">", "").onSnapshot(querySnapshot => {
  var groups= [];
  querySnapshot.forEach(function(doc) {
    groups.push({uid: doc.id, ...doc.data()});
  });
  this.setState({groups})
})