Cloud Storage for Firebase Security Rules - Using Regex Matcher

One more example of Security rules for Cloud Storage for Firebase would be using a regex.

We could use a regular expression in for our rules. This is a small one to demonstrate it.

You could require that all filenames start with “helloworld” with the following rule:

rules_version = '2';
service {
  match /b/{bucket}/o {
    match /Photos/{userUID}/{filename} {
      allow read: if request.auth.uid == userUID;
      allow write: if request.auth.uid == userUID
            && filename[0:10] == "helloworld"
            && request.resource.size <= 2 * 1024 * 1024;

Then in the code you would simply prepend “helloworld” to the beginning of every filename:

        mPhotoFilename = "helloworld" + new Long(System.currentTimeMillis()).toString() + ".jpg";

As expected, the ability to match regular expressions in your security rules is super powerful. Once you’ve finished your design then consider what the rules should be for your filenames being uploaded and write a regex to block nonconforming ones.