How to perform server validations based on query r

2019-09-14 13:29发布

When inserting a record I need to be able to run one or more queries on the server which will reject the insert if it finds any results. Will Firebase allow me to do this? It can't be specified on the client or it could be easily subverted.

For a more concrete example, I have a Meteor app that currently let's me do rate limiting on votes with some pretty simple code. I would like to implement this in Firebase. (Please forgive the CoffeeScript)

    @VoteFrequency =

      votesPer: (sinceDelta, sinceUnit) ->
        Votes.find(
          pollId: @pollId
          ip: @ip
          createdAt:
            $gte: moment().add(-sinceDelta, sinceUnit).toDate()
        ).count()

      withinLimits: (ip, pollId) ->
        @ip = ip
        @pollId = pollId

        # Allow x votes per y seconds
        @votesPer(10, 'seconds') < 1 &&
          @votesPer(1, 'hours') < 15 &&
          @votesPer(1, 'days') < 150

As you can see, it queries the database for previous votes matching the IP address and more recent than a timestamp (calculated using a delta from current time - interval). If it finds any results for any of these limits, it returns false, which tells the caller not to insert the new vote.

To be clear, I'm not looking for a solution where I add my own server into the mix. Once I have to do that, FireBase loses much of its appeal to me at least.

From what I can tell so far, this doesn't appear to be something I can implement just with a browser / native client and firebase alone.

1条回答
聊天终结者
2楼-- · 2019-09-14 13:58

You cannot run your own code on Firebase's servers. So trying to map an existing three-tier solution to Firebase will require more than evaluating how to port each script.

As far as I can see you with these main options:

  1. you implement the same logic in Firebase's security rules
  2. you run this code on a server of your own that acts as a middle tier between your clients and Firebase
  3. you run this code on a server of your own, that acts as a "bot" to a Firebase database.

I'll assume #1 is clear, though certainly not trivial. For example: Firebase's security rules don't have access to the IP address of the client, so you'll have to find a way to (securely) insert that into the data. Also: rate-limiting is possible in Firebase security rules, but not easy.

#2 is probably also clear. But it would keep you on your current three-tier architecture with custom middle-ware. You'd just be replacing your current data store with Firebase. If that's what you're looking for, this is definitely the simplest migration approach.

#3 is described in pattern 2 of this blog post. In this case you could consider letting the clients write their vote and IP address to a "staging" node. The bot-script then reads them from the staging area, validates that they are within the rules and writes to the official node (where regular clients don't have access).

查看更多
登录 后发表回答