Search code examples
firebasegoogle-cloud-firestorefirebase-securitycontains

Using contains() with firebase rules


I am trying to set a custom rule in Firestore using the following documentation: https://firebase.google.com/docs/reference/security/database/#containssubstring

I'm using the custom claims for this.

What works:

match /calendar/{calendar} {
    allow read: if request.auth.token.customData == "calendar-read,calendar-write";
}

What doesn't work and I don't know why:

match /calendar/{calendar} {
    allow read: if request.auth.token.customData.contains("calendar-read");
}

This will give me: "FirebaseError: Missing or insufficient permissions"


Solution

  • Since you are using Firestore, you should use the API documentation for Firestore String, not Realtime Database String. You will see that there is no method called "contains" for Firestore strings.

    If you want to check if there is a substring contained within a string, you should use matches() instead, and provide a regular expression to match with.

    allow read: if request.auth.token.customData.matches(".*calendar-read.*");
    

    The above should return true if request.auth.token.customData contains the string "calendar-read" anywhere within it.

    If you are using a comma-separated list of values, consider instead using split() and list.hasAny() to be more clear.