Firebase Firestore - 基于 "where" 查询参数的安全规则

Firebase Firestore - security rule based on "where" query parameters

我正在尝试保护对集合的请求以允许任何单个 get,但仅当匹配特定键时才允许 list

数据库结构是这样的:

posts
  post1
    content: "Post 1 content"
    uid: "uid1"
  post2
    content: "Post 2 content"
    uid: "uid1"
  post3
    content: "Post 3 content"
    uid: "uid2"

我从 Vue 进行的 Firestore 查询:

// Only return posts matching the requested uid

db
  .collection("posts")
  .where("uid", "==", this.uid)

我想要的安全规则是这样的:

match /posts/{post} {
  allow get: if true // this works
  allow list: if [** the uid in the query **] != null

我想这样做,这样你就可以列出特定用户的帖子,如果你知道他们 uid 但不能列出系统的所有 posts

有没有办法访问安全规则中请求的.where(),或者在这种情况下我如何编写这样的规则或构建我的数据?

相关及学分:

目前无法使用安全规则来检查某个字段是否正在查询中使用。您唯一可以做的就是验证文档字段是否仅使用您允许的值用作过滤器。

相反,请考虑将足够多的数据复制到另一个组织如下的集合中:

user-posts      (collection)
  {uid}         (document using UID as document ID)
     posts      (subcollection)
       {postId} (documents using post ID as document ID)

这将需要客户端调出一个UID进行查询,以获取与该用户关联的所有post。您可以根据需要存储尽可能多的关于 post 文档的信息,以满足查询的目的。

像这样复制数据在 NoSQL 数据库中很常见。如果您不希望用户在任何给定时刻查询所有 post,您甚至可能希望将其设为新的默认结构。请注意 collection group query naming the "posts" subcollection would still query across all posts for all users, so you'd have to make sure your security rules are set up 以便仅当您允许它发生时才启用它。

另请注意,UID 通常不会对用户隐藏,特别是如果您的网站本质上是协作网站,并且您将多个用户的数据组合在一个页面上。