2
votes

In firebase, storage feature is comfortable. But I have two questions to use storage feature.

  1. How to prevent users' unlimited file upload? e.g) if I can write /{uid}/{timestamp}/{fileName} path, user can upload till the storage is exploded.
  2. How to trace legacy files and remove them? If a user upload chat message with image file and remove the image, file still exists in the storage. Is there any hook to manage this?

Thank you!

1

1 Answers

1
votes

Good questions:

You can use Firebase Storage Security Rules to enforce arbitrary constraints for uploads. As long as the file has a piece of unique identifying information in the name or the metadata, you can tie that to a user and enforce time based access (among other things). A quick example:

match /files/{userId}/{fileName} {
  // Only allow the authorized user to write to their files
  allow write: if request.auth.uid == userId;

  // Allow reads if the resource was created less than an hour ago
  allow read: if resource.timeCreated < request.time + duration.value(60, "m");
}

You're asking for a garbage collection system :) The short answer is that it's best if you perform any file deletes along side any database object deletes on the client, but as we all know clients are unreliable. You can also set up a batch job (say every day) that reads the database data from a private backup, checks which blobs are no longer referenced, and deletes them. You can also wait for Google Cloud Functions, and perform actions (such as writing to the database on file upload) to sync this information. Lastly, you can use Object Lifecycle Management methods to clean up objects (delete, archive, etc.) in your bucket after a certain period of time.