xrd xrd - 1 year ago 77
Javascript Question

Setting limits on file uploads via Firebase auth and storage without server in the middle?

I'm learning about Firebase auth and storage in a web app. My idea asks users to login via Firebase and then upload an image.

I can see that this is possible from Firebase auth and storage. However, I would like to put limits on the file count and file-size they can upload.

Is it possible to control uploads within the Firebase console (or somewhere else)? After reviewing the JavaScript examples, I see how I can put files in, and I can imagine writing code which would query Firebase for a user's upload count, and then limit on the client side, but of course, this is a completely insecure method.

If I hosted this as a single page app on, say, GitHub pages, I am wondering if I could set these limits without involving a server. Or, do I need to proxy my uploads through a server to make sure I never allow users to upload more than I intend them to?

Answer Source

You can limit what a user can upload through Firebase Storage's security rules.

For example this (from the linked docs) is a way to limit the size of uploaded files:

service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    match /images/{imageId} {
      // Only allow uploads of any image file that's less than 5MB
      allow write: if request.resource.size < 5 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');

But there is currently no way in these rules to limit the number of files a user can upload.

One approach that comes to mind would be to use fixed file names for that. For example, if you limit the allowed file names to be numbered 1..5, the user can only ever have five files in storage:

match /public/{userId}/{imageId} {
  allow write: if imageId.matches("[1-5]\.txt");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download