Firebase 存储规则 - 意外的“userId”

Joã*_*nha 5 firebase firebase-security reactjs firebase-storage

我正在尝试设置一个规则,在 firebase 中进行存储,只有经过身份验证的用户才能编写他的名为 avatar 的头像图像

这是firebase 文档示例:

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

这些是我在 storage.rules 文件中定义的规则:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }

    match /images/{allPaths=**} {
      allow write: if request.resource.size < 5 * 1024 * 1024
                    && request.resource.contentType.matches("image/.*")
                    && request.resource.contentType == resource.contentType
    }

    match /images/user-{userId}/avatar.* {
      allow read;
      allow write: if request.auth.uid == userId;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

当我部署时抛出的错误是

[E] 13:25 - 意外的“userId”

我在文档中找不到任何其他内容告诉我如何定义这个 userId。文档指定了它,我做错了什么?

小智 5

就像两位评论者所说的那样,语法不允许“文件夹”带有 -

所以你必须选择像这样的结构

/images/user/{userId}
Run Code Online (Sandbox Code Playgroud)

制定这样的规则:

match /images/user/{userId}/avatar.* {
  allow read;
  allow write: if request.auth.uid == userId;
}
Run Code Online (Sandbox Code Playgroud)