【问题标题】:Firebase UID vs document-id and Firestore RulesFirebase UID 与文档 ID 和 Firestore 规则
【发布时间】:2020-06-10 14:43:47
【问题描述】:

您好,我在这里对 Firebase 用户 UID 和 Firestore 文档 ID (userId???) 感到有些困惑...并寻求帮助 :-)

通过创建用户,我得到一个 UID 并将其写入数据库

 let db = Firestore.firestore()
 db.collection("user").addDocument(data: [
 "name": "confused",
 "uid": result!.uid ])

通过这样做,我得到了一个唯一的文档 ID(标记为绿色),我认为它也是 userId:

我想要实现的是用户只能读写他的文档(绿色)而不能读写其他文档(红色)

因此我使用了以下规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /user/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

所以 UID 和文档 ID (userId???) 应该有联系吧?但我真的不明白?!在我的应用程序中,我想检索用户的文档 ID,以便稍后在 http-trigger 上使用它,但我只能获取 UID

print(Auth.auth().currentUser!.uid)

有什么想法还是我完全搞错了?

【问题讨论】:

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


    【解决方案1】:

    使用用户的UID作为自己文档的ID是正常的。现在,您使用的是addDocument,它告诉 Firestore 为文档分配一个随机 ID。这样,安全规则将无法按预期工作(因为 Firebase Auth 分配的 ID 永远不会与 Firestore 分配的文档 ID 匹配。您应该改为使用 setDocument 并将 Firebase Auth 中的 UID 指定为文档 ID写。

    【讨论】:

    • 好吧,这是有道理的,但是规则不正确 - 对吧?或者为什么可以写数据库?
    • 对不起,我不明白你在问什么。
    • 我使用了 Firestore 规则,因此用户只能读/写他的文档(屏幕截图中的绿色)。正如您指出的那样,我犯了错误并且不等于文档 ID 和 UID。但我仍然能够编写数据库 - 为什么会这样?
    • 没有看到你的新代码和规则,是不可能的。请提出一个新问题,说明您的新情况以及未按您预期的方式工作的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2021-02-27
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多