Ad

Firestore Rules: How Do I Allow Access To A Subcollection Depending On A Field Of The Document That Contains It?

I am writing a small program in react that manages a league of sorts.

The problem I have is how do I allow access (read, write) to the matchdays of a league for the correct user. The matchdays are named "matchday-1", "matchday-2", and so on, and are collections of documents (the matches), and are subcollections inside the league.

My firebase structure looks like this basically: leagues(collection) -> league(document) -> matchday-n(collection) -> match-m(document) where n and m are numbers.

Here's the issue:

The league document contains a field called "creator", which contains the ID of the user that created that league. Only they are supposed to access it and its matchdays!

But as it seems, when I am accessing a matchday, the value for resource.data.creator in the firebase rules is different from when I am accessing the league itself.

My question is: Which rule do I have to implement, so that only the user who created the league can access it and its subcollections?

I tried to find a way to compare the request.auth.uid to the creator of the league.

I tried something like this as a condition: request.auth.uid == get("path-to-league").creator , as you can see in the code I provided. But it doesn't seem to work this way, as I might be referencing the path incorrectly.

This is my code at the moment:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /leagues/{league} {
      allow read, write: if request.auth.uid == resource.data.creator
      }
    match /leagues/{league}/{document=**} {
        allow read, write: if request.auth.uid == get(/databases/$(database)/documents/leagues/$(league)).creator
    }
  }
}

Depending on how I fiddle with the rule set, but in case of my provided code, I get "missing or insufficient permissions" when trying to access (read or write from) a league that has the wrong creator, which is good, but even if it's the correct creator, I cannot access the matchdays.

Ad

Answer

You're missing a bit of syntax. It should probably be this:

match /leagues/{league}/{document=**} {
    allow read, write: if request.auth.uid ==
        get(/databases/$(database)/documents/leagues/$(league)).data.creator
}

Note that there is a data property before creator. This gives you access to the raw field values of the document Resource object.

Ad
source: stackoverflow.com
Ad