0
votes

Dynamic Firestore rules ?

I have 2 collections and I control access but granting customClaim. Now if I have more and more collections rules will become long.

Example

service cloud.firestore {
  match /databases/{database}/documents {
    match /india/{documentID} {
    allow read, write : if request.auth.token.india_admin == true
    allow read : if  true
    }

  }

  match /databases/{database}/documents {
    match /japan/{documentID} {
    allow read, write : if request.auth.token.japan_admin == true
    allow read : if  true
    }

  }

}

Is there a way I can generalize it by using collection name variable

1
I'm not really sure what you're trying to accomplish here. You can use a wildcard in the collection name for the rule to make a variable that you can use to match custom claims in a rule. Is that what you're trying to do? It might help if you were more specific about saying what you want to secure, and the conditions under which you want to secure it.Doug Stevenson
I have many collections and I will have ${collection}.admin custom claim for some users. Now instead of hardcoding rules for each collection I want to write single rule where collection is variableforvaidya
Doug Stevenson - yes you have captured my intent correctlyforvaidya
Could you edit your question with a sample that works for exactly one collection, so we can see specifically what you're trying to do?Doug Stevenson
request.auth.token is a Map. I don't see a way to look up a key with concatenated string in there.Frank van Puffelen

1 Answers

3
votes

What you're doing now allow unconditional read access to everything. That's what allow read: if true does.

Try this, using a wildcard for the collection name:

match /{country}/{documentID} {
  allow read, write : if request.auth.token[country + "_admin"] == true;
}

Note that this has the side effect of being applied to ALL of your top-level collection, even those that don't represent a country. If you use other top-level collections that require different rules, you might want to push all of your country-specific collection into subcollections under a single top-level collection.