代码之家  ›  专栏  ›  技术社区  ›  Jonas Sourlier

Firestore查询管道中的执行顺序-为什么缺少权限?

  •  0
  • Jonas Sourlier  · 技术社区  · 4 年前

    我的Firestore集合包含每个用户一个文档,用户ID是文档的ID。

    我有以下规则:

        match /mycollection/{userId} {
          allow read, update, delete: if userId == request.auth.token.email;
          allow create, update: if request.auth.uid != null && userId == request.auth.token.email;
        }
    

    这保证了

    • 每个用户都可以阅读、更新和删除“他们的”文档,
    • 新用户可以创建“他们的”文档。

    当我“按ID”加载用户的文档时,这非常有效。

    但是,当通过查询加载文档时,它不起作用:

    const query = db.collection("mycollection")
      .where("user", "==", userId)
      .where("writeDate", ">", writeDate)
      .get()
    

    如您所见,用户只加载“他们自己的文档”,因此在我看来,请求满足访问规则。然而,我还是遇到了“权限缺失或不足”的错误。

    为什么?

    我想这与Firestore上查询和规则的执行顺序有关,但我在文档中没有找到任何与此相关的内容。只要我只访问我有权阅读的文件,一切都应该很好,不是吗?

    如果您想知道:我只需要在文档发生更改时(因此使用“日期”where子句)才需要查询来下载文档。我知道我可以通过实时更新(使用 onSnapshot 或类似)。我不想知道其他方法。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Jonas Sourlier    4 年前

    找到了。以下规则不起作用:

        match /mycollection/{userId} {
          allow read, update, delete: if userId == request.auth.token.email;
          allow create, update: ...
        }
    

    这些规则确实有效:

        match /mycollection/{userId} {
          allow read, update, delete: if resource.data.user == request.auth.token.email;
          allow create, update: ...
        }
    

    这个 userId 仅当通过其ID访问文档时才有效。

    如果规则基于文档的某个字段(此处: user ),它需要将字段用作 resource.data.user .