1

I have the following Firestore query which can be invoked by a non-Firebase user (the sessionId is just a session id - not a Firebase user id):

const q = query(collection(firestore, "apples"), where("sessionId", "==", sessionId));

I am thinking that I need a Firestore rule to prevent access to the whole apples collection. I just want the user to access the documents where the sessionId field matches the sessionId of the requester.

I tried (which does not work):

match /apples/{appleID} {
   allow read: if request.resource.data.sessionId == resource.data.sessionId;
}

But if I have understood the reference correctly - request.resource is only available on write requests.

How can I solve this issue?

allegutta
  • 5,626
  • 10
  • 38
  • 56
  • If not using Firebase auth, it might be easier to route requests through Cloud functions or so. – Dharmaraj Feb 13 '22 at 13:39
  • This is not possible in security rules. You are not given access to the filters of the query. You might want to consider copying the documents into sucollections organzied by their session ID. Then you can query against only that narrower "view" of the data without exposing everything in a single collection. Maintaining duplicate data like this is very common in NoSQL type databases. – Doug Stevenson Feb 13 '22 at 14:44
  • What does " the `sessionId` of the requester` mean here? If `sessionId` is a property of the user, consider [setting it in a custom claim](https://firebase.google.com/docs/auth/admin/custom-claims) for that user. When you do that, it'll be available in the security rules too under `request.auth.token.yourcustomclaim`. – Frank van Puffelen Feb 13 '22 at 15:49
  • @DougStevenson Thanks, that seems like the solution I have to go with in this case. When mentioning that it is common to have duplicate subcollections, do you mean that it is common to place duplicates of a collection's documents in a subcollection due to access control? – allegutta Feb 13 '22 at 17:20
  • @FrankvanPuffelen The data is accessed by "peoples" that are not Firebase users, thus I cannot use the custom claim. But, I did read through the Firebase Auth docs now, and it seems like I can create anonymous users. Then I can use the anonymous user's Firebase user-id instead of sessionId (?). That might be a solution. – allegutta Feb 13 '22 at 17:20
  • Anonymous sign-in could help indeed, giving your users a persistent UID, without requiring them to provide credentials. – Frank van Puffelen Feb 13 '22 at 18:07
  • For NoSQL databases, it is common to duplicate documents in *any* scenario that helps your queries or access controls (not just the one you present here). Denormalization is normal. – Doug Stevenson Feb 13 '22 at 18:21
  • Very insightful and helpful feedback. Thank you both, Doug and Frank! Much appreciated. – allegutta Feb 13 '22 at 19:22

0 Answers0