Firebase security rules: check which fields are allowed in an object

I am trying to prevent unwanted fields from being added to user objects. -> User can have phone and username (but not necessarily -> newData.hasChildren (['phone', 'username']) doesn't work here). I tried this first:

"users": {
    "$uid": {
        "$other": {
            ".validate": "['phone', 'username'].indexOf($other) > -1"
        }
    }
}

      

I am getting an error because of the array :(

So, I thought about doing something like this, but it's really not great if I have a lot of potential fields

"$other": {
    ".validate": "$other === 'phone' || $other === 'username'"
}

      

Finally, I created a node in my Firebase called "rules" and did the following:

"rules": {
    "users": {
        "fields": {
            "phone": true,
            "username": true
        }
    }
}

      

And then my new validation rule in my user object is:

"$other": { 
    ".validate": "root.child('rules/users/fields/'+$other).val() === true"
}

      

My question is, is it correct to limit field names?

Thanks a lot for your answer :) I'm new to Firebase but really enjoy trying this!

+3


source to share


1 answer


To restrict an object in your Firebase to only the keys specified, try using one additional lookup child that will match any attributes not already specified, and reject the entry if it contains one of these unmatched attributes:



"rules": {
  "users": {
    "$userid": {
      ".validate": "newData.hasChildren(['phone', 'username'])",
      "phone": {
        ".validate": "newData.isNumber()"
      },
      "username": {
        ".validate": "newData.isString()"
      },
      "$other": {
        ".validate": false
      }
    }
  }
}

      

+8


source







All Articles