0

My database:

{ "user" :
    "$userID": {
        "name" : "Anon",
        "age" : 99
    }
}

If client accidentally sends incorrect data but with some valid data, is there a way to update the server only with the valid data?

For example,

user1.updateChildValues(["name" : "John Snow", "age" : 30, "BADKEY" : "BAD DATA"])

I want the above update attempt to work, but only update the database with ["name" : "John Snow", "age" : 30] in the above situation using database security rule. Is there a way to do this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
hanjustin
  • 169
  • 2
  • 9
  • not sure but i'm afraid you cant do that. You should get a little more into your real problem. What is causing you to want to do this kind of thing? – adolfosrs Jun 27 '16 at 16:32
  • I have been reading [separating public & private data](http://stackoverflow.com/questions/19891762/firebase-security-rules-public-vs-private-data) into two complete different nodes. AFAIK, for the user database ref will need to be broken down to `users-public` & `users-private`, but I was trying to see if there is a different/better way of doing it for my specific use case due to how I have stuffs implemented in the client side. In the end, I probably will have to change client side codes & restructure my database. – hanjustin Jun 27 '16 at 17:12

1 Answers1

1

It sounds like you want to enforce a schema on your data structure. You can do this in your security rules, by validating the properties (and rejecting unmatched properties):

{ "user" :
    "$userID": {
        ".validate": "newData.hasChildren('name', 'age')",
        "name": {
            ".validate": "newData.isString()"
        },
        "age" : {
            ".validate": "newData.isNumber()"
        },
        "$other": {
            ".validate": false
        }
    }
}

The $other rule here matches any children that are not matched by the more explicit rules, and then rejects them.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I probably didn't explain my problem clearly. When client sends `["name" : "John Snow", "age" : 30, "BADKEY" : "BAD DATA"]`, I wanted the database to interpret this as `["name" : "John Snow", "age" : 30]` and update the database accordingly. The answer you gave me gives me 'permission denied' for `["name" : "John Snow", "age" : 30, "BADKEY" : "BAD DATA"]` due to the extra key-value-pair. I wanted a rule that is more loosen up than the rule you wrote. In the end, what I am trying to do might be a bad practice and something not supported in Firebase. – hanjustin Jun 27 '16 at 18:01
  • 1
    Bad data should be rejected, not silently ignored. – Frank van Puffelen Jun 27 '16 at 18:05