0

I want to allow read permission on a file in Firebase Storage only if the value of a certain node in the Firebase Realtime Database is true. Is it possible to do so? If yes, then how?

  • https://www.google.com/search?q=How+can+we+write+a+security+rule+for+Firebase+Storage+that+is+dependent+on+a+value+in+the+Firebase+Realtime+Database%3F – Frank van Puffelen Jul 12 '21 at 06:00

1 Answers1

2

That is not possible at this time. You would have to use Cloud functions or your own servers using the Admin SDK to do that.

The Admin SDK essentially has full access to your Firebase project's resources so you can check if the value you are looking for in the Admin SDK exists. If yes, proceed with getting the signed URLs (or the data you are looking for from storage) else return an error.

A simple cloud function for that would be something like:

exports.getStorageData = functions.https.onCall((data, context) => {
  const {uid} = context.auth;
  const {fileName} = data;

  if (!uid) return {error: "User not authorized!"}

  // Read for data in realtime database
  const dbRef = admin.database().ref("/path/to/data");

  if ((await dbRef.once("value")).val()) {
    return {error: "Required Value is not true"}
  }

  //Get signed URL or any data from storage
  const storageRef = admin.storage().bucket()
  //.....
  return {data: "..."}
});

You need to use such secure env such as server or functions as only client side validation is not secure. But is the true value in your database something like a role or anything? You can try adding those in Custom Claims. I'm not totally sure about your use case but if it something like allowing access to specific folders or something then you can add a claim the_folder_id: true. This is not the best solution if a user can have access to a lot of folders. In that case you can assign groups as mentioned in the documentation. But satisfies your needs then you can try the following security rules along with this.

// Allow reads if the group ID in your token matches the file metadata's `owner` property
// Allow writes if the group ID is in the user's custom token
match /files/{groupId}/{fileName} {
  allow read: if resource.metadata.owner == request.auth.token.groupId;
  allow write: if request.auth.token.groupId == groupId;
}
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84