问题
I am using Stripe for payments. For this, I have the following data model in Firestore:
Users/{userId}/payments/{document}
each {document}
is an object that looks like:
{
amount: 55
token: {...}
charge: {...}
}
Users must be able to to write the token
field (this is what gets passed to the server), but I don't want users to be able to write the charge
field.
Currently my rules allow any user to read and write to this document:
match /payments/{documents} {
allow read, write: if request.auth.uid == userId;
}
What Firestore Rules will achieve my desired security?
回答1:
I believe something along the following would work, it allows clients to update fields except for charge, as well as create documents that don't have the charge field.
service cloud.firestore {
match /databases/{database}/documents {
function valid_create() {
return !(request.resource.data.keys().hasAll(["charge"]));
}
function valid_update() {
return request.resource.data.charge == resource.data.charge
|| (valid_create()
&& !(resource.data.keys().hasAll(["charge"])))
}
match /payments/{userId} {
allow read: if request.auth.uid == userId;
allow create: if request.auth.uid == userId
&& valid_create();
allow update: if request.auth.uid == userId
&& valid_update();
}
}
}
来源:https://stackoverflow.com/questions/48314542/firestore-rules-to-restrict-write-access-to-a-specific-field-in-a-document