Ad

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?

Ad

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"
Ad
source: stackoverflow.com
Ad