0
votes

I'm new to firestore and I try to get all resources from a group of users. In my case I use the auth token to keep track of user groups (I will use this on cloud storage too).

The group object is similar to:

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

Then in auth token I set the group UID:

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

Then in firestore rules I want to set something like this:

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

But now i can just get or update a document when I have the group ID and the rule to read the docs don't allow me to find all groups that user is in to list then.

The code that I tryed to run is:

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

the only solution that I think (but not tested yet) is get every group from auth token and make a request for avery one, but I think this is probably not a good one.

I already test using firestore resource object name and id and even inserting the id inside the document.

1

1 Answers

0
votes

Finally I got this. For who is trying some like this, here is my code.

The rules:

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

The client 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})
})