Search code examples
firebasegoogle-cloud-firestorefirebase-security

firestore security rules / check field type in nested object


How do I use belows generic function for nested fields? I have this document below which lives at /userdata/{uid}:

enter image description here

As can be seen userBirthTime is a map, it contains another map called birthTime which in turn has the fields I want to veryify for their types e.g. check that the incoming year is of type int before it's allowed to be stored in firestore.

How would I do this? Is it even possible for nested fields? I tried with

function isInteger(fieldName) { return request.resource.data[fieldName] is int }

and then used it like this

isInteger('userBirthTime.birthTime.year')

with the overall security rule being this

match /userdata/{uid} {
  allow write: if isInteger('userBirthTime.birthTime.year')
}

but that's just always returning true even if I try with a string as fieldName rather than the required int type?!

What am I doing wrong? Is it the fact that's a nested field and not a top-level one?


Solution

  • Apparently the dot notation doesn't work in security rules (although it returns false always):

    enter image description here

    // the request body
    "data": {
      "userBirthTime": {
        "birthTime": {
          "year": "string"
        }
      }
    }
    

    Changing the rules to this works for me:

    function isInteger(fieldName) { 
      return request.resource.data.userBirthTime.birthTime[fieldName] is int 
    }
    
    match /userdata/{uid} {
      allow write:  if isInteger('year'); // other fields
    }