如何设置 Firestore 安全规则?resource.data:空值错误

Moh*_*ran 8 firebase firebase-security google-cloud-firestore

我需要一些帮助来制定 Firestore 工作的安全规则。

这些是我的firestore规则:

service cloud.firestore {
  match /databases/{database}/documents {
     match /orders/{orderID} {
       allow read, update: if  request.auth.uid == resource.data.buyerId  || request.auth.uid == resource.data.sellerId;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的订单集合:

orders: {
sellerId: 'some-id',
createdAt: timestamp,
buyerId: 'some-id'
}
Run Code Online (Sandbox Code Playgroud)

它应该返回来自订单集合的所有文档,其中买方 ID 或卖方 ID 等于授权用户 (request.auth.uid)。

但上述规则没有按预期工作。

Firestore 集合截图

Firebase 模拟器输出

Dou*_*son 8

该错误消息表明所请求的文档实际上并不存在于数据库中。您输入了“orders/{orderId}”,这看起来就像您在模拟器的 Location 字段中放置了一个通配符。那是行不通的。如果要测试使用其字段值的规则,则需要输入存在的实际文档的路径。


Ole*_*i.B 5

resource.data: Null - 当您尝试创建新实体时会发生此错误。

拆分write规则,上createupdate

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /user/{userId} {
      allow read: if request.auth.uid == userId;

      function authed() {
        return request.auth.uid == userId;
      }
      allow create: if authed() && request.resource.data.keys().hasOnly(['name']);
      allow update: if authed() && request.resource.data.diff(resource.data).changedKeys().hasOnly(['name']);
      allow delete: if authed();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)