HelloWorld
HelloWorld

Reputation: 1863

How to calculate Firebase storage consumption per user?

I am building a desktop application and use the Firebase SDK. I am doing experiments with the Realtime Database and the Storage service of Firebase. The realtime database contains all the meta data, and the storage contains the actual files.

The database scheme looks like this:

-+ users/
 |
 + -- + sd798f7a98dsf79879/ <-- user.uid
      |
      + -- + projects/
           |
           +---- Project1/
           |     ...
           +---- Project2/
                 ...

The storage scheme looks similar. In the desktop app I can quickly calculate the total size of all files the user has in the storage since this information is stored in the realtime database. And if a user wants to upload more data than his plan allows, I could refuse the upload in the client.

But this is not 100% secure, as this is a client check that could be hacked. I am not too worried if someone could temporarily go over his limit, but I would like to ensure that I can make use of a soft and hard limit.

Given my situation using the database in a desktop application, could you recommend an alternative approach?

Upvotes: 2

Views: 906

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50930

But this is not 100% secure, as this is a client check that could be hacked.

This is true. You should never rely on client to update such data. The easiest option would be to use Cloud Storage Triggers for Cloud functions which will update the size of image in the database.

How do you actually prevent users from uploading new files if they have exceeded their quota?

The best option is to store their total usage in a custom claim and read that in Firebase storage security rules. A rule like this should work:

allow write: if request.resource.size + request.auth.token.size < 10 * 1024 * 1024;

This rule will allow users to upload files totaling 10 MB only. There maybe a rare condition where user can upload over this limit if the claim is yet to be updated.

You can check one of my answers on a similar question:

How to limit total size of files that a user can upload to Firebase storage?


As commented by @FrankVanPuffelen, custom claims take time to propagate and may allow users to upload over the specified limit. You can definitely delete the images or revoke user's refresh token (current ID Token still stays active) but that may not be good for user experience. You could also read total usage from realtime database directly before user tried to upload any files to prevent them from being uploaded. This still can be reverse engineered.


If you need to enforce these limits without such drawback, it'll be best to upload images through a Cloud function or a server which will reject the upload request if user has exceeded the quota.

Upvotes: 3

Related Questions