Firebase实时数据库规则检查数组包含



我的身份验证令牌包括一个stores属性。此属性是一个数组,其中包括允许用户访问的所有存储的ID。例如:CCD_ 2。

现在,在我的Firebase实时数据库中,我正在保存特定于商店的数据,如下所示:

{
"stores": {
"abc123": {
"data": "mydata"
},
"def456": {
"data": "mydata"
}
}
}

如果用户的stores属性数组包含他们想要访问的storeID特定数据,则允许用户访问实时数据库数据。

我希望我的规则看起来像什么:

{
"rules": {
"stores": {
"$store_id": {
".read": "auth.token.stores.includes($store_id)"
}
}
}
}

这是不可能的。我得到以下错误:

Error saving rules - line 5: type error: function call on target that is not a function.

是否可以通过firebase规则中的令牌属性数组进行搜索,或者我必须使用对象?谢谢你的回答!

Firebase实时数据库没有任何includes()来检查数组中是否存在值。您可以将索赔存储为地图而不是阵列,如下所示:

// custom claims
{
stores: {
store1: true,
store2: true,
store3: false
}
}

然后,您可以使用以下规则来检查用户是否可以访问特定的商店:

{
"rules": {
"stores": {
"$store_id": {
".read": "auth.token.stores[$store_id] == true"
}
}
}
}

您可以使用List 中的in运算符

v在x中
检查值v是否存在于列表x中。

'a' in ['a','b'] == true

示例安全规则如何进行

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {

match /stores/{storeId} {
allow read: if isAuthenticated() && isUserAllowed();
}

function isAuthenticated() {
return request.auth != null;
}
function isUserAllowed() {
return request.auth.uid in resource.data.stores
}
}
}
}

最新更新