google-cloud-firestorefirebase-security

How to check if attribute matches in an array of maps


Previously, I had the following rule:

 allow read: if request.auth.token.email in resource.data.shareWith;

Now, that the data structure changed and shareWith is no longer an array of email addresses, but an array of maps, how can I adapt this rule accordingly?

This is how the DB looks like now:

enter image description here

shareWith: [ { email, phone }, { email, phone }, ... ]


Solution

  • Checking whether an item is in an array in Firestore (both its query API and its security rules) requires that you specify the full item. There is no way to check for a partial match.

    The common workaround is to add an additional array field to each document with just the values that you want to check/query for. So in your case, that'd be:

    shareWithEmails: ["email1", "email2"]
    

    And then your security rule would be:

    allow read: if request.auth.token.email in resource.data.shareWithEmails;
    

    Also see: