Firestore安全规则:对请求使用hasOnly来检查是否仅更新特定字段 [英] Firestore security rules: Using hasOnly on a request to check if only a specific field is updated
问题描述
我正在设置Firestore安全规则,但是遇到一个问题,在这个问题中,我想限制使用hasOnly函数仅更新文档中的一个特定字段.问题是我一直在使用模拟器获得被拒绝"的结果.我肯定在做一些简单的错误...我试图防止有人可以更新文档中除update_requested_time
以外的其他字段,但是允许他们更新该特定字段.
I'm setting up my Firestore security rules, but run against one issue wherein I want to limit updating only one specific field within a document by using the hasOnly function. The problem is that I keep getting 'denied' results using the simulator. I'm surely doing something simple wrong... I'm trying to prevent that somebody could update other fields in the document than update_requested_time
, but allow them to update this particular field.
在hasOnly()上使用Firestore文档中的示例— ['a', 'b'].hasOnly(['b', 'a']) == true
—该规则返回true.但是,当我使用自己的方法时,并没有这样做,因此我认为request.resource.data.keys()
部分出了点问题.
When using the example from the Firestore documentation on hasOnly() — ['a', 'b'].hasOnly(['b', 'a']) == true
— the rule returns true. But when using my own it does not, by that I assume I'm getting something wrong in the part of request.resource.data.keys()
.
特定场景中的特定规则定位字段:
The specific rule targeting fields in a specific scenario:
match /scenarios/{scenario} {
allow read: if true;
allow update: if request.auth.uid != null
&& request.resource.data.keys().hasOnly(['update_requested_time']) == true;
我正在发送的模拟器请求(通过身份验证更新):
{"__name__":"/databases/(default)/documents/scenarios/test1","data":{"update_requested_time":"2019-02-05T11:00:00.000Z"}}
我的完整规则:
service cloud.firestore {
match /databases/{database}/documents {
match /scenarios/{scenario} {
allow read: if true;
allow update: if request.auth.uid != null
&& request.resource.data.keys().hasOnly(['update_requested_time']) == true;
match /comments/{comment} {
allow read: if true;
allow create: if request.auth.uid != null;
allow delete,update: if request.auth.uid != null && request.auth.uid == resource.data.user;
}
match /outputs/{tile} {
allow read: if true;
}
match /mutations/{tile} {
allow read: if true;
allow create,update: if request.auth.uid != null;
}
}
match /users/{user} {
allow read: if true;
allow update: if request.auth.uid != null && request.auth.uid == user;
}
}
}
推荐答案
request.resource.data
本身不包含请求数据,而是在写操作之后包含资源的新版本.因此检查失败.
request.resource.data
doesn't contain the request data itself, but it rather contains the new version of the resource after the write operation. Therefore the check failed.
request.resource
上的Firestore文档:
Firestore documentation on request.resource
:
新资源值,仅在写入请求中出现.
The new resource value, present on write requests only.
这篇关于Firestore安全规则:对请求使用hasOnly来检查是否仅更新特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!