gpt4 book ai didi

firebase - 在 Firestore 安全规则 "List"操作中使用变量

转载 作者:行者123 更新时间:2023-12-02 19:32:00 25 4
gpt4 key购买 nike

我正在尝试根据子集合中文档字段的值设置允许访问集合的安全规则。

当通过 id 检索单个文档时,这会按预期工作,这是一个 get 操作。但是,当查询 main_collection (list 操作)时,此操作会失败并出现“权限被拒绝”错误。由于集合中只有一个文档,因此这并不是我对某些正在查询的文档没有权限的情况,例如 this question .

我的数据库结构如下所示。它包含列出的集合 (main_collection),该集合具有单个文档 (some_doc),该文档具有单个子集合 (sub_collection),其中有一个文档 (another_doc)。

/main_collection/some_doc/sub_collection/another_doc

another_doc 有一个字符串字段 someFieldValue

对于此示例,我的查询是整个集合,即单个文档。在我的实际应用程序中,它只查询它期望访问的文档,但这里的最终结果是相同的,因为我无法从客户端库中过滤文档的子集合。

firestore.collection('main_collection').get()

这些是我的安全规则。

service cloud.firestore {
match /databases/{database}/documents {
match /main_collection/{mainColDoc} {
// This operation works
allow get: if subCollectionDocumentHasField('someFieldValue');
// This operation fails with permission denied
allow list: if subCollectionDocumentHasField('someFieldValue');

// This checks for the existence of a field on the subcollection's document
function subCollectionDocumentHasField(fieldName) {
return get(/databases/$(database)/documents/main_collection/$(mainColDoc)/sub_collection/another_doc).data.keys().hasAny([fieldName]);
//return get(/databases/$(database)/documents/main_collection/some_doc/sub_collection/another_doc).data.keys().hasAny([fieldName]);
}
}
}
}

subCollectionDocumentHasField 函数检查文档 another_doc 中是否存在 someFieldValue 字段。在此函数中,如果我将 $(mainColDoc) 变量替换为硬编码文档 ID some_doc,则 list 操作成功。由于 $(database) 路径变量可以在这种情况下使用,我希望其他变量也可以。

这是错误还是预期行为?

最佳答案

这实际上是预期的行为,您无法使用 Firebase 的规则来过滤查询结果

<小时/>

一个典型的场景是消息集合,其中每条消息都引用其创建者。

您不能简单地添加一条规则,仅允许阅读创建者是经过身份验证的用户的消息,以自动过滤当前经过身份验证的用户的消息。

唯一的方法是在客户端使用过滤器进行查询(或通过云函数)。

<小时/>

文档对此非常清楚:

When writing queries to retrieve documents, keep in mind that security rules are not filters—queries are all or nothing. To save you time and resources, Cloud Firestore evaluates a query against its potential result set instead of the actual field values for all of your documents. If a query could potentially return documents that the client does not have permission to read, the entire request fails.

From Firebase's documentation

关于firebase - 在 Firestore 安全规则 "List"操作中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54453697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com