如何在Firebase中添加规则以防止读取父元素? [英] How to add rule in Firebase to prevent read of parent element?
问题描述
我有一个Firebase数据库,我希望只允许有权访问该应用程序的用户能够对其进行读写。
我的数据结构是这样的:
{
"applications": {
"id_1": {
"feature": {
"a": true,
"b": false
},
"users": {
"user_id_1": true,
"user_id_2": true
}
}
}
}
如您所见,每个应用程序可以有许多具有读/写访问权限的用户。
我只希望users
对象中的用户能够检索该应用程序。
我的规则如下:
{
"rules": {
"applications": {
".read": "auth != null",
".write": "auth != null",
"$appId": {
".write": "data.child('users').child(auth.uid).val() === true",
".read": "data.child('users').child(auth.uid).val() === true"
}
}
}
}
".read": "auth != null",
允许任何登录的用户能够检索所有应用程序。我只希望用户user_id_1
或user_id_2
能够阅读该应用程序。
在伪代码中,我会这样做:
{
"rules": {
"applications": {
".read": "only users in `root.applications.$appId.users` can read", // I need to replace `$appId` some how
".write": "auth != null",
"$appId": {
".write": "data.child('users').child(auth.uid).val() === true",
".read": "data.child('users').child(auth.uid).val() === true"
}
}
}
}
如何才能限制用户user_id_1
获取其应用程序时,他们只能看到他们有权访问的应用程序?
推荐答案
您在这里遇到了几个常见问题,因此让我们逐一进行检查。
1.安全规则无法过滤数据
您试图在/applications
上的规则中控制当用户尝试读取该节点时将返回哪个应用程序。遗憾的是,这是不可能的,因为安全规则授予全有或全无访问权限。
/applications
(及其下的所有数据),也可以不访问。您不能在/applications
上设置规则以授予它们对某些子节点的访问权限。
在文档中,这称为rules are not filters,permission cascades。
2.避免嵌套数据
您试图授予对/applications
的访问权限,但随后在其中为每个应用程序存储了两种类型的数据。在这种情况下,通常最好将每种类型的数据存储为其自己的顶级列表。
所以在您的情况下,这将是:
{
"application_features": {
"id_1": {
"a": true,
"b": false
},
},
"application_users": {
"id_1": {
"user_id_1": true,
"user_id_2": true
}
}
}
这允许您为应用程序用户及其功能授予单独的访问权限。虽然这意味着您必须从两个分支读取才能获得每个用户的所有信息,但由于Firebase pipelines those requests over a single socket
,性能差异可以忽略不计为了控制访问和最具伸缩性的数据结构,Firebase建议您avoid nesting data和flatten your data structure。
3.对数据库中的数据进行建模以反映应用程序的屏幕
由于授予/applications
上的任何人访问该用户下的所有数据的权限,您可能需要另一个位置来存储每个用户的应用程序列表。
我通常在我的数据库中显式显示此列表,作为另一个顶级列表:
{
...
"user_applications": {
"user_id_1": {
"id_1": true
},
"user_id_2": {
"id_1": true
}
}
}
因此,现在当您想要显示当前用户的应用程序列表时,您可以从/user_applications/$uid
加载ID,然后通过额外调用查找每个应用程序的附加信息(这些调用可以再次流水线传输)。
文档中没有这一点,但这是NoSQL数据库的常见模式。我建议查看我对Many to Many relationship in Firebase和Firebase query if child of child contains a value的回答。
这篇关于如何在Firebase中添加规则以防止读取父元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!