Search code examples
firebasegoogle-cloud-firestorefirebase-security

Firebase securityrules. How to allow access for admins stored in an array inside document?


I have a firebase firestore document where I store the admin ids in an admins array. How can I create security rules that allows reads and writes if a request userid is in that admins list.

I wonder about 3 cases:

  1. If I have this rule how do I also allow an admin to write and read:

    match /users/{uid}{
      allow read,write: if request.auth != null;
    }
    
  2. Can I make a function for example isAdmin() inside the securityrules which I can use in every rule to accept admin?

  3. Is it possible to make one (or two) rules that allows the admins to read and write everything in the database, instead of writing a rule for every collection?


Solution

  • I believe the answer is yes to all three questions:

    1. You can use the || operator
    2. Yes, functions are allowed!
    3. Yes, rules are inheritted top down

    I very much so recommend these two videos:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        function isAdmin() {
          let admins = get(/databases/$(database)/documents/roles/admins);
          return request.auth.uid in admins.data.users;
        }
        function isOwner() {
          return request.auth != null && request.auth.uid == userId;
        }
        match /{document=**} {
            allow read, write: if isAdmin();
        }
        match /users/{userId} {
          allow read, write: if isAdmin() || isOwner();
          allow create: if request.auth != null;
        }
      }
    }
    

    This rendered success for me in my test db enter image description here enter image description here

    If you haven't used the rules playground yet, it's a good place to get started: enter image description here