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

混江龙づ霸主 提交于 2019-12-11 01:19:51

问题


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?


回答1:


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");
}



回答2:


If you need a per user storage validation the solution is a little bit more tricky, but can be done.

Ps.: You will need to generate a Firebase token with Cloud Functions, but the server won't be in the middle for the upload...

https://medium.com/@felipepastoree/per-user-storage-limit-validation-with-firebase-19ab3341492d



来源:https://stackoverflow.com/questions/40513101/setting-limits-on-file-uploads-via-firebase-auth-and-storage-without-server-in-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!