代码之家  ›  专栏  ›  技术社区  ›  Ichor de Dionysos Dan Cornilescu

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

  •  19
  • Ichor de Dionysos Dan Cornilescu  · 技术社区  · 7 年前

    我想知道如何使用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 因为这是最明显的一种。 我没想到它会起作用。 另一个猜测是 map string . 两者都不正确。

    由于我不知道这可能是什么,也没有关于如何将引用转换为路径的文档,我现在不得不在这里提问。

    有人找到了解决方法吗?

    TL;博士:

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

    谢谢 丹尼斯

    3 回复  |  直到 7 年前
        1
  •  11
  •   Gerardo    7 年前

    在此行中:

    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
  •  5
  •   Rodrigo João Bertotti    4 年前

    您可以使用检查资源是否已经存在 resource == null resource != null

    例子:

    allow write: if resource == null //Only can create, not update
    
        3
  •  4
  •   Rosário Pereira Fernandes Aabid Ansar    7 年前

    根据 exists() documentation :

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

    因此,您应该将验证函数更改为:

    function validate(document) {
        return exists(/databases/$(database)/documents/$(document.reference))
    }