I have a firebase collection of documents "posts", each post document contains four fields: "likes", "dislikes", "super", and "total". I perform batch updates on the each document with following three data objects:
var data_like_obj = {
likes: firebase.firestore.FieldValue.increment(1),
total: firebase.firestore.FieldValue.increment(1)
}
var data_dislike_obj = {
dislikes: firebase.firestore.FieldValue.increment(1),
total: firebase.firestore.FieldValue.increment(-1)
}
var data_super_obj = {
super: firebase.firestore.FieldValue.increment(1),
total: firebase.firestore.FieldValue.increment(4)
}
I couldn't find a security rule that allows me to check if the increment is valid, that is only (+1, -1, or +4) and nothing else. I made the following security function:
function validVote() {
return ( ( isUpdatingField("super") || isUpdatingField("liked") || isUpdatingField("disliked") ) && isUpdatingField("total") ) &&
(( isUpdatingField("disliked") && (0 <= (int(incomingData().disliked) - int(existingData().disliked)) && (int(incomingData().disliked) - int(existingData().disliked)) <= 1) ) ||
( isUpdatingField("super") && (0 <= (int(incomingData().super) - int(existingData().super)) && (int(incomingData().super) - int(existingData().super)) <= 1) ) ||
( isUpdatingField("liked") && (0 <= (int(incomingData().liked) - int(existingData().liked)) && (int(incomingData().liked) - int(existingData().liked)) <= 1) )) &&
( incomingData().total == incomingData().super * 4 + incomingData().liked - incomingData().disliked )
;
}
// Utility Funcs
function existingData() {
return resource.data;
}
function incomingData() {
return request.resource.data;
}
The function works just fine when I tested it on the simulator, but simulator had no way to submit FieldValue.increment
object. How can I go about validating if the increment is legal?
The console simulator is very limited. It's basically just a playground where you can get accustomed to basic rules. For serious development, you should use the rules emulator that's part of the Firebase CLI to validate your rules against actual queries:
https://firebase.google.com/docs/firestore/security/test-rules-emulator
You will be able to issues queries with actual FieldValue.increment tokens and test that the changes are valid.
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