How can I validate this data structure using Firebase security rules?

So far no luck with Firebase security rules.

I have it

{
    "rules": {
       "users": {
          "$user_id": {
            ".read": true,
            ".write": "auth !== null && auth.uid === $user_id",
            "profile": {
               ".validate": "newData.hasChildren(['first_name', 'last_name'])"
            }
         }
      }
    }
}

      

I am sending data for profile too and one of them is empty ... it allows it to write in any way. I end up with data like this ...

{
  "users" : {
    "simplelogin:25" : {
       "profile" : {
          "first_name" : "John",
          "last_name" : ""
       }
  },
    "simplelogin:26" : {
      "profile" : {
        "first_name" : "Bob",
        "last_name" : ""
      }
    }
  }
}

      

Any help on how to get the above rules to work? He may not be able to check it correctly.

+3


source to share


1 answer


Validation rule:

".validate": "newData.hasChildren(['first_name', 'last_name'])"

      

Thus, new data is valid if it has properties first_name

and last_name

.

You send this object:

"profile" : {
  "first_name" : "John",
  "last_name" : ""
}

      



This object has a property first_name

and last_name

therefore it is valid according to your rule.

It sounds like you want the properties not only to exist, but also to be strings and have a minimum length. If this is indeed your requirement, you can write it down in your validation rules:

"profile": {
   ".validate": "newData.hasChildren(['first_name', 'last_name'])",
   "first_name": {
       ".validate": "newData.isString() && newData.val().length >= 10"
   },
   "last_name": {
       ".validate": "newData.isString() && newData.val().length >= 10"
   }
}

      

The first .validate

ensures that has (at least) first_name

and last_name

properties. Other rules .validate

ensure they are of the correct type and minimum length.

+4


source







All Articles