Firestore Security Rules - How can I check that a field is/isn't being modified?

前端 未结 9 611
孤城傲影
孤城傲影 2020-11-29 07:24

For the life of me, I cannot understand why the following is resulting in a false for allowing writes. Assume my users collection is empty to start

9条回答
  •  爱一瞬间的悲伤
    2020-11-29 08:16

    So in the end, it seems I was assuming that resource.data.nonExistentField == null would return false, when it actually returns an Error (according to this and my tests). So my original solution may have been running into that. This is puzzling because the opposite should work according to the docs, but maybe the docs are referring to a value being "non-existent", rather than the key -- a subtle distinction.

    I still don't have 100% clarity, but this is what I ended up with that worked:

    function isAddingRole() {
      return !('role' in resource.data) && 'role' in request.resource.data;
    }
    
    function isChangingRole() {
      return 'role' in resource.data && 'role' in request.resource.data && resource.data.role != request.resource.data.role;
    }
    
    function isEditingRole() {
      return isAddingRole() || isChangingRole();
    }
    

    Another thing that still puzzles me is that, according to the docs, I shouldn't need the && 'role' in request.resource.data part in isChangingRole(), because it should be inserted automatically by Firestore. Though this didn't seem to be the case, as removing it causes my write to fail for permissions issues.

    It could likely be clarified/improved by breaking the write out into the create, update, and delete parts, instead of just allow write: if !isEditingOwnRole() && (isOwnDocument() || isAdmin());.

提交回复
热议问题