Allow update on single field in firestore

为君一笑 提交于 2019-11-27 06:10:25

问题


I want to give a user the right to update a document. But ONLY if the user updates one specific field of this document. All other fields shouldn't be changed by this user.

Is this possible in firestore?

I tried something like this:

function isUpdateToOpenField(attr) {
    return attr == get(/databases/$(database)/documents/stores/$(store)).data.open;
}

allow update: if isUpdateToOpenField(request.resource.data);

But I don't know how to compare if the update corresponds to the right field.


回答1:


Update: writeFields is no longer supported by Firestore and its functionality will eventually be removed. See this post.

Check out the writeFields variable for security rules:

allow update: if ((request.writeFields.size() == 1) && ('open' in request.writeFields));



回答2:


Since writeFields is deprecated and should not be used, you will have to examine request.resource.data. However, it always contains all of the fields of the written document (it's final state). This means that you will have to compare all of the fields of the written document to the fields of the original document in resource.data in order to make sure that only the ones that changed are the ones that you allow to be changed.

Currently this requires an explicit check for every field that could possibly be written, which is not fun to implement. The Firebase team is looking into ways of making this sort of rule easier to express by allowing you to diff the data maps of the "before" and "after" documents.




回答3:


Since request.resource.data will show the future object after the write - the only way is to check every field using the following:

   function notUpdating(field) {
     return !(field in request.resource.data)
      || resource.data[field] == request.resource.data[field]
   }

   allow update: if notUpdating('title') && notUpdating('description')

Make sure you validate that the user doesn't update all of the fields except the field you want him to have access to



来源:https://stackoverflow.com/questions/49671227/allow-update-on-single-field-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!