1
votes

Setup multiply rules for firebase.

Example with 3 database collections.

Cloud Firestore

On firebase collection of countries, all users should be allowed to read and write.

On firebase collection of cars, only admins are allowed to write.

On firebase collection of airplanes, all authenticated users are allowed to write.

not working documentation: https://firebase.google.com/docs/rules/basics#cloud-firestore

how to setup rules with correct syntax?

    // All public to include countries
    service cloud.firestore {
       match /databases/{database}/documents {
         match /{document=**} {
           allow read: if true ; 
           allow write: if true ;
         }
       }

     // check cars collection
     match /databases/{database}/documents/Cars {
        // For attribute-based access control, Check a boolean `admin` attribute
        allow read: if true ;
        allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;

    }

     // check airplanes collection
      match /databases/{database}/documents/Airplanes {
        // Allow only authenticated content owners access
        match /{database}/{userId}/{documents=**} {
          allow read: if true ; 
          allow write: if request.auth.uid == userID
        }
      }
    }
1

1 Answers

1
votes

You have a few mistakes in your rules.

  1. You have a statement that allows everyone to write every document. When there is more than one match statement that matches the current request, and one of the statements allows the request, the final verdict is ALLOW. Remove the foloving:
match /{document=**} {
    allow read: if true ; 
    allow write: if true ;
}
  1. Firestore is case sensitive. To avoid mistakes, use consistent naming convetion like camelCase or pascal_case.

  2. You have to add a document match variable at the end of match statement

This should work:

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

        match /users/{userId} {
            allow read: if true;
            allow write: if request.auth != null && request.auth.uid == userId;
        }

        match /cars/{carId} {
            allow read: if true ;
            allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
        }

        match /airplanes/{airplane} {
            allow read: if true ; 
            allow write: if request.auth != null ;
        }
    }
}