Firebase user write / read rules based on data objects

I am using firebase and my users are configured like this:

{
    "firebase-account-123": {
        "users": {
            "simplelogin:1": {
                "properties"{ "name": "john doe", "email": "user@email.com" }
                "children": {
                    "simplelogin:2":{ "name": "user 2", "email": "user2@email.com" },
                }
            },
            "simplelogin:2": {
                "properties"{ "name": "user 2", "email": "user2@email.com", "disabled": false }
            }
        }
}

      

I have "children" that account managers need to have access to. I am new to this and I am trying to solve some of the permission issues I have.

My rules currently allow users to read and write their own data.

".read": "auth.uid == $userid", ".write": "auth.uid == $userid"

Does anyone know how I can do this so that they also have the ability to write / read data (maybe only in the properties object) for the users listed in their "child" object?

+3


source to share


2 answers


If you want the user IDs listed in the bucket children

to be able to read and write data, try using the method hasChild()

in your security rules.

For example, using the same data structure that you described above:



{
  "rules": {
    ".read": false,
    ".write": false,
    "users": {
      "$userid": {
        ".read": "auth.uid == $userid",
        ".write": "auth.uid == $userid",
        "properties": {
          ".read": "root.child('users').child(auth.uid).child('children').hasChild($userid)"
        }
      }
    }
  }
}

      

+4


source


Something like this should do the trick:

".read": "auth.uid == $userid || root.child('users/'+auth.uid+'/children/'+$userid).exists()"

      

So this gives access to the node when:



  • this is already a registered user node
  • the current user logged into the system has a child node with node id

I would recommend clearing up your data structure a little to remove duplicate data in children:

{
    "firebase-account-123": {
        "users": {
            "simplelogin:1": {
                "properties"{ "name": "john doe", "email": "user@email.com" }
                "children": {
                    "simplelogin:2": true
                }
            },
            "simplelogin:2": {
                "properties"{ "name": "user 2", "email": "user2@email.com", "disabled": false }
            }
        }
}

      

+3


source







All Articles