So I'm setting up the firebase security rules for my project and for the user to have read access to a room, we need to make sure they are part of that organization. So I have a security rule like this:
root.child('organizations').child(data.child('organization_id').val()).child('user_ids').hasChild(auth.uid)
Not only is this really ugly, there are several other rules in the same statement (separated by &&/||) which have start with root.child('organizations').child(data.child('organization_id').val())
to access data from the organization variable associated with this room.
This leads to some UGLY security rules, is there any way I can make temporary variables or something like that so I can make this a lot more readable? Thank you!
This question (and my answer below) is about Firebase Realtime Database and its security rules.
If you're looking for using local variables in Cloud Firestore or Cloud Storage security rules, that is nowadays possible. Have a look at the blog post New improvements to Firestore Security Rules and the release note on Local Variables.
The Firebase Security rules language for Realtime Database doesn't have support for custom variables. This indeed leads to lots of duplication between rules.
The best solution is to write your rules in a higher-level language, that compiles into Firebase Security rules. The most well-known ones are Blaze (the grand-daddy of them all), Butane (not from Firebase itself) and Bolt (new and under very active development).
Bolt for example allows you to define (global) functions, which can easily encapsulate the repeated snippet and much more.