Firebase UID与文档ID和Firestore规则 [英] Firebase UID vs document-id and Firestore Rules

查看:51
本文介绍了Firebase UID与文档ID和Firestore规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I am getting a little bit confused here with Firebase User UID and Firestore Document ID (userId???)... and looking for some help :-)

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

By creating a user I get a UID and I write it to the database

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

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

by doing so I get a unique document-id (marked green) which I thought is the userId as well:

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

The thing I wanted to achieve is that the user can only read and write his document (green) and not the other documents (red)

因此,我使用了以下规则

Therefore I used the following rules

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

So the UID and the document ID (userId???) should have a connection do they? But I don't really get it?! In my app I want to retrieve the document id of the user, to use it later on a http-trigger but I can only get the UID

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

任何想法,还是我完全理解错了?

any ideas or do I get it completely wrong?

推荐答案

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

It's normal to use the UID of the user as the ID of their own document. Right now, you are using addDocument, which tells Firestore to assign a random ID to the document. With that, the security rule will not work as expected (because the ID assigned by Firebase Auth will never match the document ID assigned by Firestore. What you should do instead is use setDocument and specify the UID from Firebase Auth as the document ID to write.

这篇关于Firebase UID与文档ID和Firestore规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆