7
votes

How do you check for a value in an array within a firebase rule. I am trying to do something like this:

  root.child('connections/'+auth.uid).child('friends').child(someFriendId).exists()

So under the connections node for current user, if someFriendId exists in the friends array, allow access. 'someFriendId' isn't the key for the friends array, that is an auto generated ID from using the firebase push() method.

1
It looks like this is a limitation of firebase security rules, and thus the data should be structured as an object with keys instead of an array. I don't get why it would be like this, why enable use of $FirebaseArray with auto generated keys using push() if you cannot use any kind of security on the contents of the array. If anybody can elaborate on this it would be hugely appreciated.Stradosphere

1 Answers

9
votes

In general, avoid arrays in distributed data, and read up on Arrays in Firebase in the guide on structuring data.

You can't perform a "contains" in Firebase security rules. Instead, you'll want to store your users as the keys, similar to how we demonstrate this use case in the security docs.

So, given your example, the only change would be to replace the array indices with the user ids, and change the value to a boolean (or any other useful value). Then your security rules can be structured as:

root.child('connections/'+auth.uid+'/friends/'+someFriendId).exists();