Reputation: 680
Here's what I’ve written;
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /reservedUsernames/{username} {
allow update: if false;
allow create: if request.auth != null;
}
}
}
I already added a document with ID sam
and a field userId
= 122
. If I run an update on that document, see how below, it succeeds! How can I allow creations but no updates?
db.collection("reservedUsernames")
.document(searchableUsername)
.setData(["userId": userId])
Upvotes: 3
Views: 794
Reputation: 680
I managed to do it by using Security Rules:
rules_version = '2'
service cloud.firestore {
match /databases/{database}/documents {
match /reservedUsernames/{documentId} {
allow create: if request.auth != null && existingData(resource) == null
}
function incomingData(request) {
return request == null || request.resource == null || request.resource.data == null ? null : request.resource.data
}
function existingData(resource) {
return resource == null ? null : resource.data
}
}
}
This way I check if I'm updating an existing document and it passes only if I'm not!
Upvotes: 3
Reputation: 138824
When using:
.setData(["userId": userId])
It means that you're setting the data, and not updating it. The following rule:
allow update: if false;
Indeed rejects all update operations but as @DougStevenson mentioned in his comment, having it in your rules it's the exact same thing as not having it at all, because by default the rules are set to false.
Upvotes: 1