Reputation: 5768
I'm trying to write a security rule that only allows adding values of a certain type.
This is what I have now:
allow update if
get(/databases/$(database)/documents/users/$(request.auth.uid)).data.sessionID == key2
// THIS CHECKS IF THE USER IS ALLOWED TO UPDATE THIS DOCUMENT
&& request.resource.data.description is string
&& request.resource.data.endMo is number
&& request.resource.data.startMo is number
&& request.resource.data.openMO is bool
&& request.resource.data.pdf is string
&& request.resource.data.Adress == resource.data.Adress //USER can't update this field
&& request.resource.data.size() <= 40;
This works if all fields are already filled in.
SITUATION 1 -> WORKS
original doc
{
'description': 'helloworld',
'endMo': 12,
'startMo': 6,
'openMo': true,
'pdf': 'url',
'adress': 'myAdress',
}
db.collection("myCol").doc("myDoc").update({
'description': 'helloworld2',
}
SITUATION 2 -> DOESN'T WORK
original doc
{
'adress': 'myAdress',
}
db.collection("myCol").doc("myDoc").update({
'description': 'helloWorld',
}
Why isn't the rule accepting the adding of values and only the update of values that already exist?
Upvotes: 0
Views: 73
Reputation: 317382
Keep in mind that request.resource.data
always contains all of the fields in the document, after the update would succeed. This includes all existing fields in the document.
The update in situation works because the new contents of the document satisfy all the conditions.
Ths update in the second situation doesn't work because it's failing all of the checks for fields that don't already exist in the document, and are also not being provided in the update. If you want this second situation to work, you're going to have to code the rules so that the missing fields are not actually required with specific types like they are now.
Upvotes: 2