Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Storage Rules matching filename without Extension to User ID

I want to be able to store images for profiles with the filename as the user id, which I want to then use in my code so that when I find the user id i can fetch based on the ID. I'm converting the filename in my code to the user ID and I'm able to store it without a problem. I was to enforce this convention using Firebase Storage Rules and I'm having trouble trying to get the name of the file

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    },
    match /images/profile/full/{imagename}.*{
        allow read;
      allow write: if imagename == request.auth.uid;
    }
  }
}

I tried to use the above rule, but when I tried to publish it I had received error

Error saving rules - Line 6: Unexpected ','.; Line 7: Missing 'match' keyword before path.; Line 7: Unexpected '.'.; Line 7: mismatched input '.' expecting {'{', '/', PATH_SEGMENT}; Line 12: Unexpected '}'.

Is it possible to use to enforce the name of the file, and how would i be able to set the rule to ensure that the filename is the same as the user id and allow read access to everyone ?

like image 673
user3836415 Avatar asked Dec 02 '25 04:12

user3836415


2 Answers

This definitely won't work:

match /images/profile/full/{imagename}.*

You can only match full path segments, not partials like you're doing here.

So that means you have to match the full path segment, including the extension, and then sort it out in the rule's condition. Luckily the captures path segment is a string, so we can use regular expressions for this.

Something like:

match /images/profile/full/{imagename} {
  allow write: if imagename.matches("^"+request.auth.uid);
}
like image 119
Frank van Puffelen Avatar answered Dec 05 '25 02:12

Frank van Puffelen


The accepted answer didn't work for me, possibly because Firebase storage rules don't support multiline regex.

Try this:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /users/{fileName} {
      allow read, write: if request.auth != null && fileName.matches(request.auth.uid +'.*');
    }
  }
}
like image 35
Asalan Avatar answered Dec 05 '25 01:12

Asalan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!