Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase rule that needs to check for value in array (contains() in security rules)

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.

like image 304
Stradosphere Avatar asked Aug 20 '15 03:08

Stradosphere


1 Answers

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();
like image 111
Kato Avatar answered Sep 21 '22 17:09

Kato