Search code examples
firebasegoogle-cloud-firestorefirebase-security

How To DENY Access to entire Firestore database in security rules


Lets say I want to have a document in my Firestore having a key on whether to allow access to database or not.
Something like server_online = True
now in my firebase rules I want to check this rule first before going into rules for each collection and document.
I know that a complicated way of doing this is to put this thing in a function and then check this function along with other functions in my firebase rules for every access specifier, but that would be very long since i have a very long ruleset.
So how should i tackle this problem?

I wanted it to be something like.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    allow read: if get(/databases/$(database)/documents/server/status).data.status;
  match /users/{userID} {
      allow read: if request.auth.uid == userID;
      allow create
}
    

Now first the above rule will check if the variable is True and if so only then proceed to the later ones.

I know that the above code wont work, as Firebase checks the bottom most rule first and doesnt overwrite access.

Any ideas on how to tackle this problem?


Solution

  • Since overlapping rules are OR'ed together, there's no easy way to enforce your AND condition on all rules in one place.

    The shortest way I've found is to create a function (say isOnline) and then call that in all rules or in other *higher level) functions that my actual rules depend on.