How to restrict firebase storage files only for the paid user?

Viewed 471

I have the file stored in firebase cloud storage. This file will only available for the paid user download.

How to set up security rules to allow the paid user to have read access to that file?

[Updated]

I use the cloud firestore to store user collection Each user doc contain

  • uid
  • email
  • name
  • photoUrl
  • provider
  • status
  • stripeCustomerId
  • purchasedProducts << this is the array of product name

I can verify paid user by looking if the product exist in purchasedProducts array.

However, inside the security rule from Firebase storage, it seem I can't access resource (user collection) in there. Or am I missing something?

Thanks

3 Answers

There is no way to access Cloud Firestore from within the security rules for Firebase Storage.

That means the only ways to currently implement your use-case is to:

  • include the necessary information in the ID token of the user, as a custom claim, which is then also available in security rules.
  • include the necessary information about the user (probably their UID) in your security rules

Since the second approach requires that you update your rules for every paying user, it's not very common.

Setting a custom claim can be done through the Firebase Admin SDK, for example from a Cloud Function that triggers when you write their payment information to Cloud Firestore.

Once you set the custom claim it may take up to an hour before it's available on the client, and from there in the security rules. The reason for that is that the claims are included in the ID token, which only auth-refreshes once an hour. If you want to get the updated claims sooner, you can force a refresh of the user's profile on the client.

Another approach you can try is to delete a file right after it was uploaded using the functions.storage.object().onFinalize webhook - this is wehere you can access the database and check if the user was allowed to upload the file.

Even though it may look a bit 'hacky' at the first glance, this is really a precaution measure in the first place - the UI itself would restrict the upload for the "good" users. And for those who messes up with the source code and tries to circumvent the system, onFinalize would do the job.

Related