Firebase UID 与文档 ID 和 Firestore 规则

sar*_*aha 4 firebase-security swift google-cloud-firestore

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

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

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

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

屏幕截图 Firestore

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

因此我使用了以下规则

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

print(Auth.auth().currentUser!.uid)
Run Code Online (Sandbox Code Playgroud)

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

Dou*_*son 6

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