Firestore安全规则中的每个字段规则 [英] Per field rules in Firestore Security Rules

查看:51
本文介绍了Firestore安全规则中的每个字段规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆文件,每个文件都包含几个字段.如何编写仅适用于每个文档中特定字段的规则?

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
}

我如何做到这一点

  • 读取显示名称和访问级别
  • 写入显示名称
  • 不写入访问权限级别

我浏览了许多视频和Firestore文档,但没有发现任何东西可以显示出如何使用此按字段控制.

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.

推荐答案

您要查找的是使字段不可修改.您可以通过检查规则以确保请求后该字段的值与之前的值相同.

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]
}

然后我从我的 write (或 create update )规则中调用此函数:

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

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

因此在上面的示例中,任何管理员(由我的 isAdmin 函数确定)都可以修改名称字段,而其他用户则不能.

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

这篇关于Firestore安全规则中的每个字段规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆