Search code examples
firebasefirebase-realtime-databasefirebase-authenticationfirebase-security

How to block user from writing to Firebase Database? Without changing all the other rules below


I manage a blocked list, I want that users in the blocked list to be prevented from writing/reading the database (banned). But if I write this at a higher level, all the other rules below don't work for users who are not in a blocked list. Is there a way to still write it in a higher level instead of editing all the tables below?

   {
   "rules": { 
         ".write": "!root.child('blocked').child(auth.uid).exists() ",
         ".read": "!root.child('blocked').child(auth.uid).exists() ",
               "scores": {
                   "$sid": {
                  ".read": true,
                   ".write": "root.child('game').child($sid).child(auth.uid).exists()&& auth!=null"
                  },
             "games": {
                   "$sid": {
                  ".read": true,
                   ".write": "root.child('location').child($sid).child(auth.uid).exists()&& auth!=null"
  }
},...

Solution

  • Unfortunately the Firebase RealtimeDatabase rules work in a cascade way:

    Like the docs say:

    .read and .write rules work from top-down, with shallower rules overriding deeper rules. If a rule grants read or write permissions at a particular path, then it also grants access to all child nodes under it. Consider the following structure:

    That means if you allow or deny in the parent node it would override the child node rules. In your case the blocking would work but if someone is not blocked he would be allowed for all child nodes regardles what rules you wrote for them.

    You need to integrate that with a || operatotor to each child node.