【问题标题】:Firestore Security Rule not allowing two uids to access a docFirestore 安全规则不允许两个 uid 访问文档
【发布时间】:2020-09-16 14:31:31
【问题描述】:

TLDR;我想限制阅读该文档中提到的两个用户的 Firestore 文档。 Firestore 安全规则允许一个人访问,但不允许其他人访问。


在我的电子商务应用中,当客户 A 在商店 B 下订单时,会在 orders 集合中添加一个订单文档。我想设置安全规则,以便此订单只能由客户 A 或商店 B 读取。

这就是规则的样子:

match /orders/{orderId} {
  allow read:   if request.auth.uid == resource.data.cust.uid ||
                   request.auth.uid == resource.data.shop.ownerUid;
  allow write:  if < Some Condition >;
}

现在,在为客户获取订单时,我正在这样查询,它工作正常。安全规则通过它。

let query = dbFirestore.collection('orders')
    .where("cust.uid", "==", firebase.auth().currentUser.uid)
    .orderBy('statusHistory.New', 'desc')
    .startAfter(lastVisible)
    .limit(5);

query.get();

但是,当我查询商店时(如下所示),我收到权限被拒绝错误(通过安全规则)

let query = dbFirestore.collection('orders')
    .where("shop.ownerUid", "==", firebase.auth().currentUser.uid)
    .orderBy('statusHistory.New', 'desc')
    .startAfter(lastVisible)
    .limit(5);

query.get();

两个查询相似,但一个通过,另一个失败!!!

我想提的另一个事实是客户也可以拥有一家商店,因此以下是一种可能的情况:
request.auth.uid = shop.ownerUid = cust.uid = firebase.auth().currentUser.uid

我感觉这可能与规则错误有关,但我没有任何结论。


我也尝试在查询和规则中添加 shopId,但仍然失败。

let query = dbFirestore.collection('orders')
    .where("shop.ownerUid", "==", firebase.auth().currentUser.uid)
    .where("shop.shopId", "==", shopId_of_this_shop)      // <---- This
    .orderBy('statusHistory.New', 'desc')
    .startAfter(lastVisible)
    .limit(5);

规则:

match /orders/{orderId} {
  allow read:   if request.auth.uid == resource.data.cust.uid ||
                   (request.auth.uid == resource.data.shop.ownerUid &&
                    request.resource.data.shop.shopId == resource.data.shop.shopId);
}

供参考,以下是来自order文档的数据:

感谢您对此提供的任何帮助。

【问题讨论】:

    标签: javascript google-cloud-firestore firebase-security


    【解决方案1】:

    这是由于索引不存在。

    我没有为“shop.ownerUid”生成索引,因为查询失败并出现“权限错误”而不是“需要索引”。我一直关注安全规则。

    对“cust.uid”的查询正在通过,因为它有索引。

    一旦我意识到并生成了关于“shop.ownerUid”的索引和查询的状态字段,它就起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多