Per field rules in Firestore Security Rules

不问归期 提交于 2021-02-19 07:34:34

问题


I have a bunch of documents that contain a few fields each. How can I write rules that only apply to a specific field in each document?

For example, if my documents looked like this:

{
  "displayName": "John Doe", // read and write
  "accessLevel": 3 // read only
}

How could I make it so that you can

  • Read display name and access level
  • Write to the display name
  • Not write to the access level

I've gone through a lot of videos and Firestore docs and haven't found anything that shows how you would exercise this per-field control.


回答1:


What you're looking for is to make a field non-modifiable. You do that by checking in your rules that the value of the field is the same after the request as before it.

I have a simple helper function for this in my rules:

function isUnmodified(key) {
  return request.resource.data[key] == resource.data[key]
}

I then call this function from within my write (or create and update) rules:

  allow update: if isAdmin() || isUnmodified('name');

So in my example above, any admin (as determined by my isAdmin function) can modify the name field, but other users can't.



来源:https://stackoverflow.com/questions/58423627/per-field-rules-in-firestore-security-rules

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