Search code examples
firebasesecuritygoogle-cloud-firestorefirebase-security

How do I get the correct condition in Firebase Rules?


So I am trying to only allow a client to create a file it it has a certain name, but failing completely doing so.

// This is what I have tried so far:

https://firebase.google.com/docs/reference/rules/rules.List#hasAny

request.resource.__name__.split('/').hasAny('someDocument')

https://firebase.google.com/docs/reference/rules/rules.String#matches

request.resource.__name__.matches('.*someDocument')

And trying to compare the exact string from the rules-playground

request.resource.__name__="/databases/%28default%29/documents/someCollection/someDocument/someOtherCollection/thisDocument"

But all of them returned false for me.

service cloud.firestore 
{
  match /databases/{database}/documents
  {
    match /{document=**}
    {
        allow read: if true;
        allow write: if {insert correct condition here};
    }
  }
}

Solution

  • You just need a wildcard to get the value of a document ID. Try the following:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents { 
        match /collectionName/{docId} {
          allow read, write: if docId.size() > 5; // example 
        } 
      }
    }
    

    If you want to match collection name as well then you can add another wildcard like this:

    match /{colId}/{docId}  {  ...  }
    

    Checkout the documentation for more information.