Create group access to firebase storage without using custom authorization

前端 未结 2 1059
春和景丽
春和景丽 2020-12-09 00:34

Is there a way to control uploads to a path in Firebase Storage by group? For instance have an admin group that can upload anywhere or a team that can only upload to a certa

相关标签:
2条回答
  • 2020-12-09 00:49

    After searching around a bit, I didn't find a ready answer, so I'll post what I have so far. It would be nice to know if there are other (better) ways of doing this.

    Since I'm trying NOT to use another server, custom authentication tokens are out. However, the request.auth.uid is available to the storage rules. The uid property matches one of the users defined in the Auth area. You'll need to create a function in the storage rules that checks if request.auth.uid is in a group you define.

    Firebase storage rules have a unique syntax. It sorta looks like javascript, but it's not. You can define functions, but you can't declare a var within them. Furthermore there is a subset of javascript-like methods available.

    For instance, I first unsuccessfully tried the following:

    function isAdmin() {
      return ["value","list"].indexOf(request.auth.uid) > -1;
    }
    
    service firebase.storage {...}
    

    Either the rules editor threw errors when I tried to define a var OR it always returned "unauthorized" when I used .indexOf.

    The following ended up working for me.

    function isAdmin() {
      return request.auth.uid in {
        "yaddayaffffdayaddUserIDKey":"User Name1"
      };
    }
    function isSomeOtherGroup() {
      return request.auth.uid in {
        "yaddayaddaSomeOtherUID":"User Name2",
        "YaddBlahBlahUID":"User Name3"
      };
    }
    
    service firebase.storage {
      match /b/<your bucket here>/o {
        match /{allPaths=**} {
          allow read, write: if isAdmin();
        }
        match /path/{allPaths=**} {
            allow read, write: if isSomeOtherGroup() || isAdmin();
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-09 00:52

    I don't have enough reputation to comment on @ecalvo's answer. So I am adding an answer. The function isAdmin() can be provided a list as following:

    function isAdmin() {
       return request.auth !=null && request.auth.uid in [
            "uidAdmin1",
            "uidAdmin2",
            "uidOfOtherAdminsAsCommaSeparatedStrings"
        ];
    }
    

    Rest of the implementation can be borrowed from the answer of @ecalvo. I feel now it is more clear. In the answer of @ecalvo, I was confused why should I give username when I have to compare only uid.

    0 讨论(0)
提交回复
热议问题