gpt4 book ai didi

google-cloud-firestore - Firestore 根据来自不同集合的条件进行规则

转载 作者:行者123 更新时间:2023-12-05 08:20:27 27 4
gpt4 key购买 nike

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

/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

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

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

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

有关这方面的更多信息,请参阅 control access with custom claimsaccessing the user token在文档中。

关于google-cloud-firestore - Firestore 根据来自不同集合的条件进行规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50629167/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com