【问题标题】:Firebase rule to access own data, public data or specific data onlyFirebase 规则仅访问自己的数据、公共数据或特定数据
【发布时间】:2020-10-04 15:38:08
【问题描述】:

我想通过 firebase 规则和 firebase 查询来实现以下目标。 (我正在使用 firestore 和 vuejs)

前提条件:用户在任何情况下都必须是auth登录

  1. 允许用户read/write他自己创建的所有数据条目
  2. 允许用户read所有字段(在我的情况下为"visibility")设置为"public"的数据
  3. 如果用户拥有条目的id,则允许用户阅读特定条目,即使条目的"visibility" 字段设置为不等于"public"(例如"private"

假设这是我收藏的条目

从 User-A 创建第一个条目,从 User-B 创建第二个条目,从 User-C 创建第三个条目:

所以:

  1. 应该允许用户 B read/write 第二个条目(其他用户依此类推)
  2. 应该允许用户-A、B、C read 第一个和第三个条目。
  3. 如果用户 A、C 通过直接 document-id 查询等方式知道 firebase 文档的 ID,则应该允许他们使用 read 第二个条目。喜欢db.collection('my_collection').doc('abcxyz').get()

第二个问题是:我什至需要"user_id" 字段才能根据用户创建的文档过滤请求?或者,firebase 是否具有内置功能,可以根据(身份验证)检索自行创建的文档?

[
  {
    "user_id": "the User-A's firebase id",
    "foo": "foo",
    "bar": true,
    "visibility": "public"
  },
  {
    "user_id": "the User-B's firebase id",
    "foo": "foo",
    "bar": true,
    "visibility": "private"
  },
  {
    "user_id": "the User-C's firebase id",
    "foo": "foo",
    "bar": true,
    "visibility": "public"
  }
]

有人可以帮我创建规则和请求吗? (我正在使用这个 npm package

这是我现在用于检索自创条目的查询

this.db.collection("my_collection").where('user_uid','==',this.$store.state.user.id).get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        //do something 
      });
    });

这个用于创建

db.collection("my_collection").add({
    user_uid: this.$store.state.user.id,
    foo: this.foo,
    bar: this.bar,
    visibilty: this.visibility
  })

这是我到现在为止的规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore firebase-security


    【解决方案1】:

    Firestore 不会自动将文档与创建文档的用户相关联。如果您需要此类元数据,则需要像现在一样将其存储在每个文档中。

    要确保用户只能阅读自己的文档,您需要做两件事:

    1. 仅尝试读取这些文档的查询。你已经有了这个,所以☑。
    2. 允许查询但拒绝更广泛读取的规则。
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null && request.auth.uid == resource.data. user_uid;
        }
      }
    }
    

    有关这方面的更多信息,另请参阅securely querying data 上的文档。


    要允许其他用例,您需要扩展规则以允许以类似方式进行访问。但是您需要为每个案例执行单独的查询,因为 Firestore 查询不能包含多个字段的 OR 类型条件,而这正是您的用例所需要的。

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 2019-09-24
    • 2018-05-16
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多