RobertAKARobin
RobertAKARobin

Reputation: 4258

How to make a Firebase rule making sure you can only enter certain things in a field?

Let's say I'm using Firebase to run a message board in which every post must first be approved by a moderator.

Thus, a post can have one of three "statuses":

The only way I've found to make this rule is like so:

{
    "rules": {
        "posts": {
            ".write": "newData.child('status').val() == 'unreviewed' || newData.child('status').val() == 'approved' || newData.child('status').val() == 'rejected"
        }
    }
}

This seems very inefficient and not DRY. Is there another way of making sure a field's value is always one of a few values?

Upvotes: 2

Views: 60

Answers (1)

vzsg
vzsg

Reputation: 2896

The security rules language is a limited subset of JavaScript, so you cannot completely clean up the repetitions... But you can certainly shorten it a little, while making it less error-prone too.


Sidenote: Avoiding the security problem

One of the issues with your attempt is that you use .write rules to validate the data. These rules are completely ignored if any parent or higher rule grants write access to this subtree.

But fret not, you just have to move data validation to .validate rules instead. They are always evaluated and enforced on write operations – with the only exception being the admin users.


Cleaning up the rules

Restructuring the rules to follow your expected schema helps a great deal in improving readability, even if the character count is not much less.

{
  "rules": {
    "posts": {
      "$postId": {  // (1)
        ".validate": "newData.child('status').exists()", // (2)

        "status": {
          ".validate": "newData.val() == 'unreviewed' || newData.val() == 'approved' || newData.val() == 'rejected"
        }
      }
    }
  }
}
  1. I added this level because I assumed you want to store a list of posts, not just a single post under /posts.
  2. Listing the required child nodes (or "fields") should be done on the post. The validation rule for status would be ignored otherwise if it is not set in the new posts.

Also, take a look at the Bolt compiler. It helps you DRY out the security rules and generate the validation rules.

Upvotes: 2

Related Questions