首页 > 解决方案 > 将 contains() 与 firebase 规则一起使用

问题描述

我正在尝试使用以下文档在 Firestore 中设置自定义规则:https ://firebase.google.com/docs/reference/security/database/#containssubstring

我正在为此使用自定义声明。

什么有效:

match /calendar/{calendar} {
    allow read: if request.auth.token.customData == "calendar-read,calendar-write";
}

什么不起作用,我不知道为什么:

match /calendar/{calendar} {
    allow read: if request.auth.token.customData.contains("calendar-read");
}

这会给我:“FirebaseError:缺少或不足的权限”

标签: firebasegoogle-cloud-firestorefirebase-securitycontains

解决方案


由于您使用的是 Firestore,因此您应该使用Firestore String的 API 文档,而不是 Realtime Database String。您将看到 Firestore 字符串没有称为“包含”的方法。

如果要检查字符串中是否包含子字符串,则应改用matches(),并提供正则表达式进行匹配。

allow read: if request.auth.token.customData.matches(".*calendar-read.*");

request.auth.token.customData如果在其中的任何位置包含字符串“calendar-read”,则上述内容应返回 true 。

如果您使用逗号分隔的值列表,请考虑使用split()list.hasAny()来更清楚。


推荐阅读