Firebase Cloud Storage security rule for deleting
Asked Answered
R

2

4

Hi I am using Firebase Cloud Storage to develop web application. I would like to set different security rules for setting file from deleting file. It seems that write includes both of them according to the document. Does anyone know how to solve this problem?

What I would like to do is this.

  1. Anyone can set file if they are loggedin.
  2. Only user who set the file can delete it.
Rigobertorigor answered 19/6, 2018 at 2:33 Comment(2)
Cloud Functions doesn't have security rules. Only Cloud Storage, Cloud Firestore, and Realtime Database have security rules that are enforced for client apps. Cloud Functions using the admin SDK bypass these rules.Sheen
Thanks for the response. It was my mistake that I wrote Cloud Function in the title. I edited the title. I wanted to ask about Cloud Storage.Rigobertorigor
J
7

You can detect that a file is being deleted with request.resource == null in your rule.

But there is no property in the file objects (that I know of) to know who created the file.

A common approach is to store the files under a path that identifies their creator, e.g. /users/$uid/filename. With that structure you can check like this:

match /users/{userId}/profilePicture.png {
  allow read;
  allow write: if request.auth.uid == userId && request.resource == null;
}

An alternative would be to add an owner property to the metadata of each file and then check:

match /{fileId} {
  allow read;
  allow write: if (request.auth.uid == resource.metadata.owner && request.resource == null);
}
Jailhouse answered 19/6, 2018 at 2:49 Comment(1)
Great! By providing two ifs, you can make a separate rules for deleting from creating and updating. I will try this approach.Rigobertorigor
C
0

These rules allow any logged in user to upload and delete only their own files. Files must be uploaded to a path prefixed with /users/{userId}/:

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
    match /users/{userId}/{allPaths=**} {
      allow write: if request.auth.uid == userId &&
        (
          // is the request deleting this file?
          request.resource == null ||
          (
            // optional upload checks for file size and type
            request.resource.size < 20 * 1024 * 1024 &&
            request.resource.contentType.matches('image/.*')
          )
        );
        
    }
  }
}

You can add allow read: if true; to make the files publicly readable.

Complacent answered 13/3 at 17:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.