【问题标题】:Firestore rules, queries and structuring dataFirestore 规则、查询和结构化数据
【发布时间】:2020-08-18 20:58:53
【问题描述】:

我有一个使用 Firestore 保存多人存档的游戏。

基本上每个文档都有这种格式($表示一个 20 个字符的 p-随机 ID)

$savegame = {
  users = [$user1, $user2]  
  info = {turn: 2, }
  gamestate = {longjsonstring} 
} 

我使用查询数据

firebase.firestore().collection('savegamescollection').where('users', 'array-contains', firebase.auth().currentUser.uid)

我想使用 firestore 规则只允许游戏中的人更新存档,我找不到检查 firestore 规则中的 users 数组的方法。

所以我所做的是( > 表示集合)

savegame = {
  > usercol = { $user1, $user2 }   - line A
  users = [user1, user2]           - line B
...
} 

我使用规则

match /savegamescollection/{doc} { 
allow read, write: if exists(/databases/$(database)/documents/savegamescollection/$(doc)/usercol/$(request.auth.uid));

这确实有效,但有缺陷且丑陋。 我将相同的数据复制为数组中的元素和文档 ID。

有没有办法在数据结构(上面的 A 和 B)中使用这些行之一来允许查询和规则运行。

谢谢

【问题讨论】:

  • 很难根据您目前所拥有的内容来想象您正在使用的代码和数据。请编辑问题以显示 1) 您正在使用的规则无法按您期望的方式工作,2) 您尝试允许或拒绝的客户端查询,3) 您正在使用的一些特定数据与。
  • 我想我正在寻找一个可以搜索数组的规则函数。或者可以以我需要的数据中的文档 id 为条件的查询(而不是文档的值)或另一种避免重复的方法,或者澄清由于查询和规则结构不兼容而需要重复。

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


【解决方案1】:

如果您想强制用户必须使用包含数组的查询来仅请求列出用户 UID 的文档,您可以在列表字段中使用hasAny 来检查他们的 UID 是否在列表中。

match /savegamescollection/{doc} {
  allow read, write: if resource.data.users.hasAny([request.auth.uid]);
}

【讨论】:

  • 真的就这么简单,不知道怎么错过了,谢谢。
猜你喜欢
  • 2018-03-21
  • 2018-07-14
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多