Reputation: 49
I may have some problem with the syntax of the firestore security rules, because I think the logic behind my database structure is correct and also the security rules should be correct.
So the structure is as follows. I have a collection of "users", they are either buyers or sellers (of watches say). And there is a collection of "watches". Inside watches, sellers can create documents which contain details of the watch and also the id of the seller.
A document inside "watches" has a subcollection called "status". Inside "status" there is a single document, this document has a field which is also called "status", its value is either 0 or 1, 0 means it is available (for buying) and 1 means it is reserved by someone. The security rules are: only the creater of a watch document can alter that document and (any) buyer can only change the status if the status was 0.
I thought the following should do the job
service cloud.firestore {
match /databases/{database}/documents {
match /users/{$uid} {
allow read, update: if request.auth.uid == $uid;
}
match /watches/{watchId} {
allow read: if true;
allow update: if request.resource.data.sellerId == request.auth.uid;
match /status/{statusId} {
allow read: if true;
allow update: if request.resource.data.status == 0 && request.auth != null;
}
}
}
}
I did some simulations, but it never allowed me to make changes in the status (I was signed in and the status was 0). Is there something wrong with the code?
Upvotes: 0
Views: 318
Reputation: 317798
This rule:
allow update: if request.resource.data.status == 0 && request.auth != null;
Says, in English, allow an update to this document if the user is authenticated and the user is trying to set the status field to 0. This is different than what you stated in your question. Note that request
refers to stuff that's coming from the client, not the existing data in the document. If you want an auth'd user to be able to change the status only from an existing value 0 to a new value 1, then you will need to say this:
allow update: if request.auth != null // user is auth'd
&& resource.data.status == 0 // existing value is 0
&& request.resource.data.status == 1 // new value is 0
Note the difference between resource.data
, which is the existing document data, the request.resource.data
, which is the new document data.
Upvotes: 2