Search code examples
firebasegoogle-cloud-firestorefirebase-security

Restrict only one collection from writing in Firestore Database


I have several collections in Firestore and I want to prevent writing ONLY to 'products' collection.

I tried this script but it does not work:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /products/{id} {
      allow read: if true;
      allow write: if false;
    }
    match /{document=**} {
      allow read: if true;
      allow write: if request.auth.uid != null;
    }
  }
}

Solution

  • There are two ways to solve this

    Preferred

    1. According to Frank van Puffelen
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{collection}/{document=**} {
          allow read: if (request.auth.uid != null);
          allow write: if collection != 'products'; 
          // 👆 This will allow write permission to all collection except products collection.
        }
      }
    }
    

    Trivial way

    1. As @Doug Stevenson suggested in the comment and in the post.
    • Firestore security rules implement an allowlist and not a denylist.

    • So you'll have to specify rules to every other collection.

    • Only for the products collection deny the write permission

      service cloud.firestore {
        match /databases/{database}/documents {
      
          match /orders/{order} {   
            allow read, write,update,delete: if request.auth != null; //👈 Give permission to orders document
          }
      
          match /carts/{cart} {
            allow read, write,update,delete: if request.auth != null; // 👈 Give permission to carts document
          }
      
          match /products/{product} {
            allow read : if request.auth != null; // 👈 Here dont give  permission to write
          }
        }
      }