Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore rules if..else

I have just started to get my head around Firestore rules and my head is expanding rapidly.

I'm trying to work out how to apply a rule to one collection and another rule to all other collections and their sub-collections.

So I start with the default rule that seems to come with Firestore:

service cloud.firestore {
  match /databases/{database}/documents {

    match /{document=**} {
      allow read, write;
    }
  }
}

which would allow read write access to all collections and their documents.

But suppose I want to apply a rule to the documents in one collection and retain the default rule for all other collections. The following will not work:

service cloud.firestore {
  match /databases/{database}/documents {

      match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
}

  match /{document=**} {
    allow read, write;
}


 }
}

because the second rule will override the first.

Is there a way to do what I am trying to do?

like image 972
Chris Curnow Avatar asked Jun 06 '18 00:06

Chris Curnow


People also ask

How do you set rules on firestore?

To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console. Write your rules in the online editor, then click Publish.

How do I check my firestore rules?

Open the Firebase console and select your project. Then, from the product navigation, do one of the following: Select Realtime Database, Cloud Firestore, or Storage, as appropriate, then click Rules to navigate to the Rules editor.

How do I change rules in Firebase Storage?

You can edit these rules by selecting a Firebase app in the Firebase console and viewing the Rules tab of the Storage section.


1 Answers

I understand that you want to apply a rule to the documents in one collection and retain the default rule for all other collections. There's a way to do what you're trying to do and you're not going to like it.

You have to specify the default rules for all the other collections explicitly.

Here's a sample.

service cloud.firestore {
  match /databases/{database}/documents {

    //Rule for Suppliers collection
    match /suppliers/{supplier} {
        allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
    }

    //Rule for Changelog collection allowing complete access
    match /Changelog/{id} {
        allow read: if true;
        allow write: if true;
    }

    //Rule for Vendors collection allowing complete access
    match /Vendors/{id} {
        allow read: if true;
        allow write: if true;
    }

  }
}

Note: Firestore rules doesn't support if else statements. But you can use AND and OR conditions as a workaround to simulate the same.

like image 92
denniskbijo Avatar answered Sep 22 '22 06:09

denniskbijo