firebase存储检查写入模式错误中的元数据

时间:2016-07-11 13:39:48

标签: javascript firebase firebase-security firebase-storage

在我的存储规则中,我有这段代码

match /Image/{user}/{image}/image.jpg {
      allow write: if request.auth != null && (request.auth.uid == user || request.auth.uid == 'nodeserver') && (resource.metadata['private'] == true || resource.metadata['private'] == false)
      allow read: if request.auth != null && (request.auth.uid == user || resource.metadata.private == false)
    }

如果我尝试像客户端那样编写自定义元数据

 var imageRef = storageRef.child('Image/' + uid + '/' + imageId + '/image.jpg');

            var metadata = {
                customMetadata: {
                    private: false 
                }
            };

            var imgref = imageRef.put(image, metadata);

我通过firebase服务器收到此错误

POST https://firebasestorage.googleapis.com/v0/b/project-4815133492804887736.app…Image%2F39IhnMU70uYrhJ9Y0XWBEMtQDR63%2F-KMP9NDx3D2gjJix3bpL%2Fimage.jpg 403 ()
service.js:303 x {code: "storage/unauthorized", message: "Firebase Storage: User does not have permission to…hJ9Y0XWBEMtQDR63/-KMP9NDx3D2gjJix3bpL/image.jpg'.", serverResponse: "{↵  "error": {↵    "code": 403,↵    "message": "Pe…n denied. Could not perform this operation"↵  }↵}", name: "FirebaseError"}code: "storage/unauthorized"message: "Firebase Storage: User does not have permission to access 'Image/39IhnMU70uYrhJ9Y0XWBEMtQDR63/-KMP9NDx3D2gjJix3bpL/image.jpg'."name: "FirebaseError"serverResponse: "{↵  "error": {↵    "code": 403,↵    "message": "Permission denied. Could not perform this operation"↵  }↵}"__proto__: Error__proto__: Object

如果我从规则中删除此代码

(resource.metadata['private'] == true || resource.metadata['private'] == false)

一切正常,但我想验证元数据。解决方案是什么?

2 个答案:

答案 0 :(得分:1)

您想使用request.resource代替resource。这是因为resource指的是当前存在的内容(已存储的文件),而request.resource指的是请求中的资源(正在上传的文件)。

match /Image/{user}/{image}/image.jpg {
  allow write: if request.auth != null && (request.auth.uid == user || request.auth.uid == 'nodeserver') && (request.resource.metadata['private'] == true || request.resource.metadata['private'] == false)
  allow read: if request.auth != null && (request.auth.uid == user || resource.metadata.private == false)
}

请注意,read规则应使用resource,因为它指的是已存在的文件,而write规则需要引用request.resource因为那是什么被上传。

答案 1 :(得分:1)

只需将存储规则更新为:

service firebase.storage {
  match /b/barcodemanager-8dd41.appspot.com/o {
    match /{allPaths=**} {
      allow read, write;//: if request.auth != null;
    }
  }
}

就我而言,它解决了我的问题!