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?
To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console. Write your rules in the online editor, then click Publish.
If you need some value (or combination of values) to be unique, you need to create a node that contains that value (or combination) as its key. If you need to guarantee that multiple values (or combinations) are unique, you'll need multiple of such nodes.
A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries. You can create a subcollection called messages for every room document in your rooms collection: collections_bookmark rooms. class roomA.
Use the Rules PlaygroundOpen the Firebase console and select your project. Then, from the product navigation, do one of the following: Select Realtime Database, Cloud Firestore, or Storage, as appropriate, then click Rules to navigate to the Rules editor.
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(); } } }
Set type was announced, along with some other cool stuff.
Using Sets to ensure that a document only has fields "a", "b", and "c":
request.resource.data.keys().toSet() == ["a", "b", "c"].toSet()
Similarly, you could make sure that a document only has specified keys, but not others:
(request.resource.data.keys().toSet() - ["required","and","opt","keys"].toSet()).size == 0?`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With