Firestore规则来自不同的集合

时间:2018-05-31 16:47:23

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

我有一个包含两个集合的Firestore数据库:用户和锦标赛。用户具有“参与者”角色和“管理员”角色,并在用户文档中由“isParticipant”和“isAdmin”布尔值表示:

/users/{userId}:
  isParticipant: true
  isAdmin: true

我为这些集合设置了访问规则,如下所示:

service cloud.firestore {
  match /databases/{database}/documents {
     match /users/{userId} {
      allow create, read;
      allow update: if request.auth.uid == userId;
    }
     match /tournaments/{tournamentId} {
      allow create, read, update: if request.auth.uid != null;
    }
  }
}

但是,我真正想要做的是将锦标赛的创建限制为具有“管理员”角色的用户。我已经在代码中执行此操作,但希望增加db规则的安全性,以防止除管理员用户之外的任何人创建锦标赛。

有没有办法在规则语法中引用不同集合的数据元素?类似的东西:

     match /tournaments/{tournamentId} {
      allow create: if resources.users.userId.isAdmin == true;
    }

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用get功能访问不同集合中的数据:

 // Allow the user to delete cities if their user document has the
 // 'admin' field set to 'true'
 allow delete: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true

有关详细信息,请参阅Firebase文档中的access other documents,这是我从上面获取上述示例的地方。

需要注意的一点是,这需要额外的文档阅读。如果您将用户在其个人资料中的管理员作为自定义声明存储,则可以从request.auth访问它,而无需额外阅读。 E.g。

allow delete: if request.auth.token.admin == true

有关详情,请参阅文档中的control access with custom claimsaccessing the user token