30

Can we use Firestore data to grant or restrict access to files hosted on Firebase Cloud Storage?

Exemple of what I would like to use as Firebase Security Rule

allow write: if get(/databases/mydbname/documents/guilds/$(guildID)).data.users[(request.auth.uid)] in ["Admin", "Member"];
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
Remi
  • 583
  • 6
  • 17

1 Answers1

31

There is currently no way to access different Firebase products from within the security rules of another product. See: is there a way to authenticate user role in firebase storage rules?

But it seems like you are trying to check group-membership of the user. Instead of looking that group-membership up in the database, I recommend that you model it as a so-called custom claim. Instead of (or in addition to) writing the membership to the database, you'll set the claim "user {uid} is a member of group {guild1}" into the user profile using the Firebase Admin SDK:

admin.auth().setCustomUserClaims(uid, {guild1: true}).then(() => {
  // The new custom claims will propagate to the user's ID token the
  // next time a new one is issued.
});

With that done, you can check the guild membership in the security rules:

allow read: if request.auth.token.guild1 == true;

(I'm not sure if/how you can model the guild membership as a map, I'll update this answer if that turns out to be the case.)

Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
  • 1
    make sense. will try to populate custom claims based on database using cloud firestore triggers and will see if that make it – Remi Oct 21 '17 at 15:42
  • 5
    @frank-van-puffelen Is this still the case as of 2021 – Andrew Jan 28 '21 at 20:03
  • 2
    Both the fact that you can't access other products from within security rules and the workaround are still valid yes. – Frank van Puffelen Jan 28 '21 at 20:05
  • You could also do a [cloud storage trigger](https://firebase.google.com/docs/functions/gcp-storage-events) which ultimately deletes the upload if it is not validated through firebase. – Jonathan Sep 18 '21 at 22:33
  • Yup, that's always an option @Jonathan. If you can elaborate a bit more on how to do that, it might make a good alternate answer. – Frank van Puffelen Sep 18 '21 at 22:48