I want to restrict documents in certain collections to only have write access to the user whose uid
matches the document id
. This does not work, however, as it produces an invalid permission error on the client.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth != null;
}
function isOwnDocument() {
return request.auth.uid == request.resource.id;
}
match /userSettings/{doc} {
allow write: if isOwnDocument();
allow read: if isSignedIn();
}
}
}
You can pass the docId
variable directly in the isOwnDocument()
function instead of reading from the request.resource
object as shown below:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth != null;
}
function isOwnDocument(docId) {
return request.auth.uid == docId;
}
match /userSettings/{docId} {
allow write: if isOwnDocument(docId);
allow read: if isSignedIn();
}
}
}
The resource
property might be undefined
in explained in this answer.
request.auth.uid == resource.id
can be used to be but that'll throw an error if the document does not exist since your rule is works for write
ops that includes create
and update
too). This rule will work only when used with allow create:
. But best to pass the ID directly in the function parameters so it'll support both operations.