5

I am building firestore security rules for my app and in the events collection I have a property called members that has an array of references from the users collection. How would I go about making sure that the user that has sent the request is in that collection? I know I am able to get the userId through request.auth.uid but I'm unaware of how to get the document reference in firestore rules and make sure that the reference is in the array.

Sree Grandhe
  • 369
  • 2
  • 13
  • It would be helpful if you edit the question to show the rules you have so far that don't work the way you expect. Make an attempt, even if it doesn't work, and show where you're stuck. – Doug Stevenson Jul 23 '20 at 04:40

2 Answers2

7

The answer that I have found is this:

match /events/{eventId} {
  allow read: if /databases/$(database)/documents/users/$(request.auth.uid) in resource.data.members;
}

Looks like the in keyword allows me to check if a value is inside an array and /databases/$(database)/documents/users/$(request.auth.uid) creates a DocumentReference which is the data type stored in the array.

Marko K
  • 346
  • 3
  • 12
Sree Grandhe
  • 369
  • 2
  • 13
0

As clarified in this other post here, similar to yours, Firestore rules are not used for filtering data, but to set which data are accessible for which users and which queries can be performed.

Considering that, you will need to write code that will query and compare the datas from your request.auth.uid, with the ids from your subcollection. This way, you will be able to confirm the data you want, that is the user requesting being authorized to access the information. This would be the correct way to handle the request and return the information or not from your database.

A simple example of code that will confirm that the requesting users is in the members subcollection is similar to the following lines:

var user = firebase.auth().currentUser;
db.collection("events").where("members", "array-contains", user.uid).get()

While this code is untested, is a starting point for what you will need to do, to guarantee that the user requesting is allowed to retrieve the information. You can get more information on what you need here.

Let me know if the information helped you!

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22
  • Your solution is appreciated, however the idea is that I don't want people that are not part of the `members` entry in a document in the events collection to have access to that event document at all. – Sree Grandhe Jul 23 '20 at 18:19