Firestore 根据不同集合的条件进行规则

2023-11-29

我有一个 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;
    }
  }
}

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

有没有办法在规则语法中引用不同集合的数据元素?就像是:

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

?

提前致谢。


您可以使用以下方法访问不同集合中的数据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 文档中,这是我从其中获取上述示例的地方。

需要注意的一件事是,这需要阅读额外的文档。如果您要存储用户是管理员的事实inside他们的个人资料作为自定义声明,您可以从request.auth无需额外阅读。例如。

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

有关这方面的更多信息,请参阅使用自定义声明控制访问 and 访问用户令牌在文档中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firestore 根据不同集合的条件进行规则 的相关文章

随机推荐