首页 > 解决方案 > Firestore 规则:用户访问包含 userId 的集合

问题描述

我的 Firestore 中有 2 个集合

users : uid, email period : periodId, name, owner_id

我需要用户仅访问它的“用户”集合的规则,以及仅当 ownerId uid 等于经过身份验证的用户 ID 时才允许读取和写入“周期”集合的另一个规则。

我这样做

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write : if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
    
    match /periods/{periodId} {
            allow read, write : if request.auth.uid == request.resource.data. owner_id;
        }
  }

}

但它不起作用。

:(

标签: firebasegoogle-cloud-firestorefirebase-security

解决方案


您不共享与这些安全规则对应的查询,但我们已经可以确定您的安全规则中的几个问题:

1. 因为/users/{userId}你在create和之间有一些重叠write

下面将解决这个问题:

match /users/{userId} {
  allow read, update, delete: if request.auth != null && request.auth.uid == userId;
  allow create: if request.auth != null;
}

请参阅文档:“在多个允许表达式匹配请求的情况下,如果任何条件为真,则允许访问”。

2. 因为/periods/{periodId}你需要在read和之间分割write

对于读取访问权限,resource变量引用请求的文档,并且resource.data是存储在文档中的所有字段和值的映射。

对于写访问权限,request.resource变量包含文档的未来状态。

来源

所以下面应该做的伎俩(未经测试):

match /periods/{periodId} {
        allow read : if request.auth.uid == resource.data.owner_id;
        allow write : if request.auth.uid == request.resource.data.owner_id;
}

我建议您观看以下有关安全规则的官方视频。实际上整个“认识 Cloud Firestore”视频系列是必须的……


推荐阅读