带有 FirebaseRecyclerAdapter 的 Firebase 规则结构
Firebase rules structure with FirebaseRecyclerAdapter
我正在尝试使用 Firebase 平台开发一个简单的聊天应用程序。为了显示对话列表,我正在使用 FirebaseRecyclerAdapter。问题是,我不知道如何正确设置规则,以便用户只能访问他们所属的对话。
这就是我的 Firebase 数据库结构。
{
"conversations": {
"cid1": {
"title": "Conversation1"
},
"cid2": {...
},
"cid3": {...
}
},
"members": {
"cid1": {
"uid1": true,
"uid2": true
},
"cid2": {...
},
"cid3": {...
}
},
"users": {
"uid1": {
"name": "User1"
},
"uid2": {...
},
}
}
这些是我要应用的规则。
{
"rules": {
"conversations": {
"$conversation_id": {
".read": "root.child('members').child($conversation_id).child(auth.uid).exists()",
}
},
}
}
通过应用此规则并使用 FirebaseRecyclerAdapter,我收到此错误。
Listen at /conversations failed: DatabaseError: Permission denied
我想这是因为我允许用户阅读对话元素,而不是整个对话列表。有人知道如何解决这个问题吗?
您陷入了 Firebase 安全规则中的陷阱之一:您无法使用安全规则来过滤数据。
您的列表适配器正在侦听 /conversations
。根据用户是否对 /conversations
具有读取权限,该读取操作将完全成功或失败。
由于您未授予对 /conversations
的读取权限,侦听器将被取消。这被称为 Rules Are Not Filters in the documentation and has been covered frequently here on Stack Overflow (because it's such a common pitfall). For one of the oldest and still best answer, see: Restricting child/field access with security rules
我正在尝试使用 Firebase 平台开发一个简单的聊天应用程序。为了显示对话列表,我正在使用 FirebaseRecyclerAdapter。问题是,我不知道如何正确设置规则,以便用户只能访问他们所属的对话。
这就是我的 Firebase 数据库结构。
{
"conversations": {
"cid1": {
"title": "Conversation1"
},
"cid2": {...
},
"cid3": {...
}
},
"members": {
"cid1": {
"uid1": true,
"uid2": true
},
"cid2": {...
},
"cid3": {...
}
},
"users": {
"uid1": {
"name": "User1"
},
"uid2": {...
},
}
}
这些是我要应用的规则。
{
"rules": {
"conversations": {
"$conversation_id": {
".read": "root.child('members').child($conversation_id).child(auth.uid).exists()",
}
},
}
}
通过应用此规则并使用 FirebaseRecyclerAdapter,我收到此错误。
Listen at /conversations failed: DatabaseError: Permission denied
我想这是因为我允许用户阅读对话元素,而不是整个对话列表。有人知道如何解决这个问题吗?
您陷入了 Firebase 安全规则中的陷阱之一:您无法使用安全规则来过滤数据。
您的列表适配器正在侦听 /conversations
。根据用户是否对 /conversations
具有读取权限,该读取操作将完全成功或失败。
由于您未授予对 /conversations
的读取权限,侦听器将被取消。这被称为 Rules Are Not Filters in the documentation and has been covered frequently here on Stack Overflow (because it's such a common pitfall). For one of the oldest and still best answer, see: Restricting child/field access with security rules