Firestore安全规则检查引用是否存在

问题描述 投票:14回答:2

我想知道如何检查文档值是否是对另一个文档的引用,并且文档是否存在使用firebase安全规则。

我尝试了什么:

function validate(document) {
    return exists(document.reference)
}

match /collection/{document} {
    allow read: if request.auth != null;
    allow create, update: if isAdmin(request.auth.uid) && validate(request.resource.data);
}

由于这不起作用,我试图找出document.ref是什么类型。不幸的是,它似乎没有列出的任何类型:https://firebase.google.com/docs/firestore/reference/security/?authuser=0#data_types

我尝试了path,因为它是最明显的工作存在。我没想到它会起作用。另一个猜测可能是mapstring。两者都不正确。

因为我不知道这可能是什么,并且没有任何记录如何将引用转换为路径,我现在必须在这里问。

有没有人找到解决方案?

TL; DR:

我需要检查使用Firestore安全规则是否存在文档中保存的引用并且它是否存在于数据库中。

谢谢,丹尼斯

firebase firebase-security google-cloud-firestore
2个回答
5
投票

在这一行:

allow create, update: if isAdmin(request.auth.uid) && validate(request.resource.data)

而不是调用“request.resource.data”,你应该只调用“resource.data”:

allow create, update: if isAdmin(request.auth.uid) && validate(resource.data)

如上所述here,资源变量表示Firestore文档,而“request”变量表示在该路径上发出的请求,因此不包含有关文档中实际值的信息。

试一试,让我知道它是否适合你。


2
投票

根据exists() documentation

提供的路径必须以/databases/$(database)/documents开头。

因此,您应该将验证功能更改为:

function validate(document) {
    return exists(/databases/$(database)/documents/$(document.reference))
}
© www.soinside.com 2019 - 2024. All rights reserved.