One strategy could be to utilize the Admin SDK for modifying Storage Rules based on information stored in a Firestore document that tracks the daily upload count.
For example, you could have a firestore collection/document named userUploads/uid
, with fields like uploadedFiles: 0
and lastUploadedOn
.
After a user uploads a file to Firebase Storage, you can trigger a Cloud Function to check the lastUploadedOn
field against the date of the current upload. Depending on this comparison, you can update the values in the document accordingly. When the number of uploaded files reaches a limit (e.g., 10), you can adjust the storage rules using the Admin SDK as described here. Subsequently, you would reset the count in the userUploads/uid
document.
It's worth noting that rule changes may take some time to deploy, so caution is advised. As mentioned in the Admin SDK documentation:
Firebase security rules take a period of several minutes to fully deploy. When using the Admin SDK to deploy rules, make sure to avoid race conditions in which your app immediately relies on rules whose deployment is not yet complete
An alternative approach, perhaps more efficient, could involve managing access through Auth Claims
. By setting an auth claim token to restrict uploading permissions when a limit is reached, you can instantly block further uploads without the deployment delay associated with rules changes.
To revoke the auth claim:
- Utilize a cloud function within the upload error handler to monitor changes in the
lastUploadedOn
field and remove the claim accordingly
- Implement another cloud function before each upload attempt to verify the user's uploading status and adjust claims if needed
- Optionally, incorporate logic during login to check and remove claims based on specific criteria
A system based on Auth Claims offers real-time enforcement of upload restrictions and streamlined management compared to altering storage rules. It provides immediate feedback to users attempting to exceed limits or violate policies.
Note: Any modifications to auth claims must be propagated to clients. Refer to this documentation for additional guidance.