Shahzad Akram
Shahzad Akram

Reputation: 5254

Firebase different security rules for different child

I have my data structure like this.

enter image description here

I want that only admin can create a new user, only admin can write expireDate, Admin and user both can write other two fields,

I tried these dabase rules:

{
  "rules": {

      "users":{

              "$uid": {

                ".read": "auth.uid == $uid || root.child('admins').child(auth.uid).exists()",

                "expireDate":{
                                        ".write": "root.child('admins').child(auth.uid).exists()"
                },

                "firstLoginAttempt":{
                    ".write": "auth.uid == $uid || root.child('admins').child(auth.uid).exists()"
                },

                  "macAddress":{
                    ".write": "auth.uid == $uid || root.child('admins').child(auth.uid).exists()"
                }


      } 
      }

I allowed admin to write for all child but admin is unable to create a new user. I know firebase database rules override in cascade, But how to implement here.

Upvotes: 0

Views: 112

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Once you grant a user (read or write) access at a certain level in the JSON tree, you can no longer take that permission away at a lower level in the tree.

This means that:

  1. Either the data that more people can write should be at a lower level in the JSON tree.
  2. Or you will need to put the data in different top-level notes based on the requires access level.

Since your data structure doesn't follow the guidance of #1, so that mean you should follow #2.

Something like:

users: {
  user1: { ... },
  user2: { ... }
expiries
  user1: { ... },
  user2: { ... }

And then secure access between these two top-level nodes with:

{
  "rules": {
    "users":{
      "$uid": {
        ".read": "auth.uid == $uid || root.child('admins').child(auth.uid).exists()",
    },
    "expiries":{
      "$uid": {
        ".read": "root.child('admins').child(auth.uid).exists()",
    }
  } 
}

Upvotes: 1

Related Questions