首页 > 解决方案 > 在 Firebase 安全规则中使用 UID 作为映射键

问题描述

我正在使用 Firestore 构建一个聊天应用程序,每个聊天室都有一张参与者地图,如下所示:

在此处输入图像描述

键是用户对应的 UID。我想使用这张地图来决定哪个用户可以访问聊天。在我的安全规则中,我目前检查登录用户的 UID 是否存在于此映射中以允许读写访问:

allow read, write: if request.auth.uid in resource.data.participants

但这仅检查用户是否在此地图中,而不是该值是否为真。我也想检查一下。

我基本上想要的是这样的:

allow read, write: if resource.data.participants.request.auth.uid == true

但这实际上不起作用。如何在地图检查中使用当前用户的 UID 作为键?

标签: firebasegoogle-cloud-firestorefirebase-authenticationfirebase-security

解决方案


使用方括号使用您想要的任何字符串表达式对Map进行索引:

allow read, write: if resource.data.participants[request.auth.uid] == true

推荐阅读