Reputation: 95
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?
Upvotes: 4
Views: 3650
Reputation: 317392
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.
Upvotes: 6