多权限Firestore安全规则

时间:2020-02-20 10:35:14

标签: google-cloud-firestore firebase-security

我的网站有多个具有不同权限的帐户。

我在Firestore令牌中使用自定义声明,以向用户提供正确的访问权限。

到目前为止,此设置可以完美运行:

有权访问1个位置的用户1的声明如下:{"companyLocation": "testLocation1"}

很快,我将拥有可以访问一个或多个位置的用户。例如,用户2可以访问“ testLocation2”和“ testLocation3”,而无需访问“ testLocation1”。

用户2的声明可以例如具有分隔符(“¤”)并看起来像这样:{"companyLocation": "testLocation2 ¤ testLocation3"}

如何通过安全规则实现这一目标?我尝试过:

function checkMultipleLocations(){
  return request.auth.token.companyLocation.contains('testLocation2');
}

这给我一个错误说明:

无效的函数名称:包含

在文档中指出可以使用in: v in x(检查值v是否在列表x中),但这不适用于列表(不返回true),仅适用于对象/地图(尝试通过将用户声明字符串拆分为数组,没有运气)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

in运算符仅适用于列表。此声明{"companyLocation": "testLocation2 ¤ testLocation3"}的值不是列表,而是字符串。因此in运算符在这里无法使用。


有关受支持的运算符的列表,请参见string type in security rules的文档。这里没有提到contains方法,但是确实有一个matches方法,可让您完成此用例。

request.auth.token.companyLocation.matches('.*testLocation2.*')

您还可以尝试将声明存储为数组:

{"companyLocation": ["testLocation2", "testLocation3"]}

如果设置这样的声明有效,则in运算符应该有效。我在这里说应该,因为最近有人在设置这样的声明时遇到了麻烦,而我自己还没有对其进行测试。