Firebase Security Rule That Limits Writes To An Increment (+1) Of Current Value?
I'm building a very simple JavaScript-based Firebase app that increments a key's value by 1 whenever my webpage is loaded. I don't want any authentication friction, so want to use either an open database, or one restricted to anonymous authentications. So, for example's sake:
$(document).ready(function() {
// after config and initialize...
var fb = firebase.database();
var fbCount = fb.ref("count");
fbCount.transaction(function(current) {
return current + 1;
});
});
In either case, as I understand it, there is nothing to stop anyone who can access the page from copying my code (including my initialization config) and using it on their own server--with adjustments--to not only increment the value (fbCount
above), but to change the code in any other way they like (e.g. letting them increment the value by 100, 1000, or changing it to something else entirely).
My further understanding is that the best way to deal with this potential is through security rules. So what I'm trying to figure out is whether there's a way, through the security rules, to limit any write to only an increment by 1 of the current value?
If not, is there another method I should be investigating?
Answer
You'll want to make use of predefined variables. Your validation rule will look something like this (at the location of the field you want to protect):
".validate": "newData.val() == data.val() + 1"
Related Questions
- → How can I query Firebase for an equalTo boolean parameter?
- → How can I access nested data in Firebase with React?
- → Firebase simple blog (confused with security rules)
- → Removing item in Firebase with React, re-render returns item undefined
- → AngularJS Unknown Provider Error (Firebase & AngularFire)
- → How do you pass top level component state down to Routes using react-router?
- → "this" is null in firebase query function in reactjs
- → Angular Module Failed to Load
- → Multiple dex files define Lcom/google/android/gms/internal/zzrx;
- → Joining Firebase tables in React
- → How can I make add firepad to my reactjs project?
- → How to use Cloud Functions for Firebase to prerender pages for SEO?
- → React.js component has null state?