Bi CURE
Bi CURE

Reputation: 35

Firebase Rules: How to search all children of a node for a value?

I'm trying to create admins for an app by manually entering them in Firebase based on their Twitter login generated uid. I'm wondering how I can search all of the children under a node for a specific uid to specify r/w access.

I have the following

{
  "GRP1" : {
    "ORG1" : {
      "CONF1" : {
        "TEAM1" : {
          "ADMINS" : {
            "Name1" : {
              "uid" : "abcd1239"
            },
            "Name2" : {
              "uid" : "abcf1234"
            }
          },
          "FEED" : {
            "Store1" : {
              "info1" : "some text"
            },
            "Store2" : {
              "info2" : "some other text"
            }
          }
        }
      }
    }
  }
}

I want to provide r/w access to FEED based on if the uid exists in ADMINS. This rules works:

".read" : "root.child('GRP1').child('ORG1').child('CONF1').child('TEAM1').child('ADMINS').child('Name1').child('uid').val() === auth.uid"

But if I have variable number of ADMINS, how do I search through all of the 'uid'? I have tried entering the child name as the uid, then searching to see if it exists but the read would not work:

".read" : "root.child('GRP1').child('ORG1').child('CONF1').child('TEAM1').child('ADMINS').child(auth.uid).exists()"

Upvotes: 1

Views: 238

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

You can't search across nodes in security rules, as that would not scale. This means that if you want to check whether the UID exists in a certain place in your JSON, you must have that UID as the key of the node.

So your JSON would be:

{
  "GRP1" : {
    "ORG1" : {
      "CONF1" : {
        "TEAM1" : {
          "ADMINUIDS" : {
            "abcd1239": "Name1",
            "abcf1234": "Name2"
          }

Now you can check for the existence of the UID with:

".read" : "root.child('GRP1/ORG1/CONF1/TEAM1/ADMINUIDS').child(auth.uid).exists()"

Upvotes: 1

Related Questions