Home > Enterprise >  Firebase upload protection
Firebase upload protection

Time:11-25

I'm building an app where users can upload an image. I use firebase as the backend. Now since all logged-in users can upload, how do can I manage this safely? The image is uploaded via firebase storage and then the URL is saved to Firestore. I have two options in mind:

  • An URL is added to Firestore and then the image can be uploaded. This has the advantage that after a new Firestore document is added I can give the user permission to upload a file. The disadvantage is that after a document is added the upload can fail. This will mean that there is a URL in Firestore without an image in Storage.
  • The image is uploaded to Storage and then the Firestore document is added. This has the advantage that every document does have an image attached but this also means that every user can upload every image that they want, without me having any control.

I do use firebase cloud functions but if I add the document first the cloud functions are invoked while the image may not be done uploading. What is the best way to tackle this problem?

CodePudding user response:

If you thought you can add to a batch operation, a Firestore addition operation, and a Firebase Storage file upload operation and be sure that both are complete, so you can have consistent data, please note that this is not possible. These operations are a part of different Firebase services and unfortunately, at the moment I'm writing this answer there is no way you can make them atomic.

As far as I know, none of the Firebase products support cross-product transactional operations. To solve this, you'll have to nest the calls during your addition/upload operations and handle the error if the second operation fails. This means that you either have to delete the document from Firestore if the upload operation in Cloud Storage fails or vice versa.

But note, at some point in time, there will be a failure that the client can't roll back one of the delete operations. The most common approach for these inevitable failures that might happen, is to make your code robust by handling exceptions and performing occasional cleanups in both places, Firestore, and Firebase Storage.

CodePudding user response:

You could set up a user auth claim like "can_upload_pics" then check this claim whenever the user initiates an upload, you might want to use firebase functions to add custom claims. If done right the second option will work as expected checkout this video for a good explanation and example for custom claims

  • Related