Reputation: 851
I would like to guarantee that an user can only add a document that has the same id that its auth.uid.
For example, an user with id 1X0T6xC6hhRN5H02zLCN6SQtwby2 can only create/update the document /salesmen/1X0T6xC6hhRN5H02zLCN6SQtwby2 .
At app level, it's done by the following command (both for create and update).
this.db
.collection("salesmen")
.doc(user.uid)
.set(data)
.then(function() { //...
At Firestore level, I am trying the following rule, but it's not working (it results in Error writing document: Error: Missing or insufficient permissions.).
match /salesmen/{salesman} {
allow read: if true;
allow write: if request.auth != null && resource.id == request.auth.uid;
}
How can this rule be enforced ?
Upvotes: 3
Views: 1038
Reputation: 317562
resource.id
can only be used to refer to an existing document in Firestore. It doesn't work if the document being written doesn't exist yet.
Instead, you can use the salesman
wildcard in your match expression to determine if the user can write a particular document, even if it doesn't exist yet:
match /salesmen/{salesman} {
allow read: if true;
allow write: if request.auth != null && salesman == request.auth.uid;
}
It looks like you can also use request.resource.id
to reference the id of the document that possibly has not been written yet:
match /salesmen/{salesman} {
allow read: if true;
allow write: if request.auth != null && request.resource.id == request.auth.uid;
}
Though I can't find that explicitly discussed in the reference documentation as of this moment.
Upvotes: 8