Firebase UID vs document-id and Firestore Rules

本秂侑毒 提交于 2020-12-12 11:35:07

问题


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

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 ])

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;
    }
  }
}

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?


回答1:


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.



来源:https://stackoverflow.com/questions/60418788/firebase-uid-vs-document-id-and-firestore-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!