【问题标题】:Firestore rules to access collection that matches Auth uid访问与 Auth uid 匹配的集合的 Firestore 规则
【发布时间】:2021-07-26 02:16:59
【问题描述】:

我正在尝试设置我的安全规则,以便用户可以完全访问一个特定文档(以其 UID 命名)以及此“父”文档中的所有子文档。

我为此创建了以下规则,但是当我尝试读取/写入子文档或父文档时,我收到错误“调用者没有权限”。

虽然通配符语法会涵盖我这里。我的理解显然存在差距。

service cloud.firestore {
  match /databases/{database}/documents {
    match /User/{document=**} {
      allow read, write: if request.auth.uid == document
    }
  }
}

数据库布局

用户

  • uid1
    • 随机文档名
    • 随机文档名
  • uid2
    • 随机文档名
    • 随机文档名
  • uid3
    • 随机文档名
    • 随机文档名

与后端接口的代码

db.collection("User")
   .doc(uid1) //this is set as a prop via auth UID of user, parent
   .collection(randomDocumentName) // this is the child document
   .add({
         name:'test'
       })

【问题讨论】:

  • 规则自己不会做任何事情。请编辑您的问题以包含可以重现该错误的最少代码。在该代码中,请务必记录任何明确满足您的规则条件的值(即:记录用户的 UID 和您正在写入的路径)。
  • 收集方法中的“randomDocumentName”是什么?您似乎正在尝试为子集合编写规则。它叫什么名字?还是可变的?
  • 目前称为成员,我计划添加更多这些子集合,例如配置,图像等。因此我放了随机名称。它是 UID 文档的子集合。我目前在“成员”中有其他文件,我希望遵守这些规则。即如果 auth uid 与父集合名称匹配,则允许访问 uid 文档和所有子集合

标签: firebase google-cloud-firestore firebase-authentication firebase-security


【解决方案1】:

这可能有效

service cloud.firestore {
  match /databases/{database}/documents {
    match /User/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

【讨论】:

  • 这个修复没有骰子,我等着看它是否还需要传播,但我怀疑这是问题
  • @AWebster 确保集合名称在规则中也完全相同。
【解决方案2】:

使用规则游乐场后解决了这个问题。

首先我根本没有查看父文档的权限,然后我授予每个用户访问特定子文档的特定文档权限。 如果我添加一个新的子文档,我需要添加一个规则。

service cloud.firestore {
  match /databases/{database}/documents {
    match /UserData/{ID}{
    allow read, write :if request.auth  != null && request.auth.uid == ID;
    // allow users to create and access their parent document
    }
  
    match /UserData/{userId}/randomDocumentName/{doc=**} {
      allow read, write :if request.auth != null && request.auth.uid == userId; // allow read and write to the documents they own
    }
  }
}

【讨论】:

  • randomDocumentName 是如何生成的?
  • 我在第一次授权uid时批量写入初始化它。我将 randomDocumentName 硬编码为 members 到路径 User/[UID]/randomDocumentName 。
猜你喜欢
  • 1970-01-01
  • 2021-02-27
  • 2022-06-15
  • 1970-01-01
  • 2019-08-15
  • 2018-11-27
  • 2020-06-10
  • 2019-08-17
  • 1970-01-01
相关资源
最近更新 更多