Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Security Rules for Storage

I have just started using Firebase and I am able to read/write/edit/delete to the database. In my app I only show data to the user if he/she has access to it.

I do that by creating a user node and another node (call it services) and reference the services in that users child node.

I have never used Firebase's security rules before, and I now want to starting using Firebase Storage for images.

I am following a tutorial and my console said,

Permission denied. Could not access bucket.. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources

Upon googling and searching on SO on how to set up these security rules I am not sure what is the right answer. Some answers suggest I write methods in my code to grant permission, but the documentation suggests that I need to do it on Firebase's end.

This is one of the examples

// Grants a user access to a node matching their user ID
service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    // Files look like: "user/<UID>/path/to/file.txt"
    match /user/{userId}/{allPaths=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

I cannot make sense of peoples answers

Like this one from a few months ago

    {
  "rules": {
    "UsersDB": {
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid"
      }
    }
  }
}

Can somebody please explain for the current Firebase (and for iOS Swift..if it matters) how to just make it so user 1 can only read/write his/her data/photos

like image 550
RubberDucky4444 Avatar asked Feb 20 '17 08:02

RubberDucky4444


1 Answers

You need a corresponding File Path structure:

For example when you upload the file store them like this:

(root…) /user/uidxxx/myfile.jpg

Where "uidxxx " is the Unique User ID defined in your authentication database.

Then on the console/storage / Rules tab you can write the rule:

// Grants a user access to a node matching their user ID
service firebase.storage {
  match /b/<your-firebase-storage-bucket>/o {
    // Files look like: "user/<UID>/path/to/file.txt"
    match /user/{userId}/{allPaths=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

{userId} is a wildcard that will be replaced by the corresponding "uidxxx"

like image 70
ThierryC Avatar answered Nov 16 '22 02:11

ThierryC