Cloud Storage for Firebase Security Rules - Using File Metadata

In one of the previous posts we used the file size to restrict the file size.

Cloud Storage for Firebase Security Rules provides many ways to use the file metadata, known as resource evaluation.

Here are our rules so far:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /Photos/{userUID}/{filename} {
      allow read: if request.auth.uid == userUID;
      allow write: if request.auth.uid == userUID && request.resource.size <= 2 * 1024 * 1024;
    }
  }
}

We have a lot of resource evaluation rules we can apply. Go to your .write rule and start typing “&& resource” and autocompletion will fire and give you hints:

Screen Shot 2019-07-21 at 3.08.20 PM.png
Screen Shot 2019-07-21 at 3.08.30 PM.png
Screen Shot 2019-07-21 at 3.08.41 PM.png

A very nice feature!

Choose request.resource.contentType and let’s add another .write rule to ensure an image is the type of file being written:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /Photos/{userUID}/{filename} {
      allow read: if request.auth.uid == userUID;
      allow write: if request.auth.uid == userUID 
            && request.resource.size <= 2 * 1024 * 1024
          && request.resource.contentType.matches('image/.*')
    }
  }
}

Add the additional metadata for contentType to our Simulator test. You’ll notice that Size is still retained in the metadata:

Screen Shot 2019-07-21 at 3.49.33 PM.png

Try the Simulator and see that its successful!

Publish the rules to save them!