0

We're having trouble with rules in Firestore. We want to restrict writes such that if a certain field is written to, then the write will be denied.

match /users/{email} {
  allow read: if true;
  allow write: if !isWritingProtectedUserField();
}

function isWritingProtectedUserField() {
  return request.resource.data.keys().hasAny(['restricted']);
  // should allow a write when data is {"something": "val"}
  // should deny a write when data is {"restricted": "val"}
}

This rule works as expected in the rules simulator. However, when attempting to write actual data, the rule gives permission-denied every time.

Thanks in advance.

T Mack
  • 950
  • 3
  • 12
  • 27
  • 1
    Note that any other answers you might find on Stack Overflow that discuss use of "writeFields" are out of date. That technique is no longer supported and could eventually stop working. What you have to do instead is check to see if the value of the restricted field is actually changing, then allow the write only if it is not. The rules language is improving and will make this easier in the future. – Doug Stevenson Dec 17 '19 at 01:07
  • @DougStevenson thank you for pointing me there. I adapted the answer to look like this: `function isAddingField(field) { return !(field in resource.data) && field in request.resource.data; } function isChangingField(field) { return field in resource.data && field in request.resource.data && resource.data[field] != request.resource.data[field]; } function isEditingField(field) { return isAddingField(field) || isChangingField(field); } ` Is this still going to work as expected? – T Mack Dec 17 '19 at 01:19

0 Answers0