ilgaz
ilgaz

Reputation: 61

Firebase Realtime Database: Retrieving "limited" data on "backend"

This is my first question and I hope that will bring me a good luck about my problem!

I've been working on an "free/paid" application and my main rule is for these two customers to allow Free customers only query 500 items from my Firebase Realtime database. But If they want more then have to pay for me to see all the items. But the problem is I can only make this happen on front end or client side and that makes my web application hackable..

Can you please help me, how can I limit the query result on Firebase console depending customer status?

if the user is "authenticated and paid for it" then allow him to list more than 500 result. If he is "anonymous or authenticated but not paid for it" then limit him for 500 results.

On BACKEND!

Thanks guys,

Upvotes: 2

Views: 320

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599491

That used to be impossible for a long time. But I think you might now be able to do this thanks to query based rules. This allows your security rules to validate that a query that is attached matches your rules. For example (from the documentation):

messages: {
  ".read": "query.orderByKey &&
            query.limitToFirst <= 1000"
}

So these rules only allow a query if it reads at most 1000 messages.

Example queries:

db.ref("messages").on("value", cb)        // Would fail with PermissionDenied

db.ref("messages").limitToFirst(1000)
                  .on("value", cb)        // Would succeed (default order by key)

If you store people's maximum number of items in a custom claim, you should be able to check that in the rules:

messages: {
  ".read": "query.orderByKey &&
            query.limitToFirst <= auth.token.maximumItemCount"
}

You'll note that in each of these cases, the client should also specify the correct number of items in its query. The security rules "merely" ensure that the query is allowed, they don't automatically filter the items.

My disclaimer "should" is because I never tested anything like this, so be sure to post back if you're having problems making it work.

For more info see:

Upvotes: 4

Related Questions