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

问题描述 投票:0回答:1

我是firestore的新手,我尝试从一组用户那里获取所有资源。在我的情况下,我使用auth令牌来跟踪用户组(我也将在云存储上使用它)。

组对象类似于:

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

然后在auth令牌中我设置组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。

firebase google-cloud-firestore firebase-security-rules
1个回答
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})
})
© www.soinside.com 2019 - 2024. All rights reserved.