1

I have a counter in my firebase to count likes in each post.

var databaseRef = firebase.database().ref('/posts/').child(pid).child('likes');
            databaseRef.transaction(function(count) {

so this will add +1 in each like in posts/likes after I insert it in likes/postid/userid json. To count the likes.

I made a rule for this, to allow count +1 like per time:

   "likes": {
     ".write": "newData.isNumber() && 
     ((!data.exists() && newData.val() === 1) || newData.val() === data.val()+1)"
   },

it avoid someone to put 1000 likes in a post at once, but not protect someone to run a script inserting +1 like each second... any solution for this? how to protect a counter in firebase rules?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
RGS
  • 4,062
  • 4
  • 31
  • 67
  • 1
    See my answer here: https://stackoverflow.com/questions/37954217/is-the-way-the-firebase-database-quickstart-handles-counts-secure – Frank van Puffelen May 07 '20 at 13:37
  • 1
    Is it right to assume that your problems, is that you are afraid of a user liking the same post multiple time, by making request simultaneously? – EdwinS95 May 07 '20 at 13:47

1 Answers1

2

If you execute the counter node increment from the front-end, you do need to assign the write access right to the users. There is no way to avoid some malicious users to increase it.

One solution is to implement the counter update in a Cloud Function. Cloud Functions executes in the back-end and bypass all the security rules (since they run in the back-end, they are considered as "privileged environments"). So you can deny any write access to the counter node.

You should use a Cloud Function which is triggered when a post is updated, see https://firebase.google.com/docs/functions/database-events

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121