我一直在努力从最近的研究中了解如何实现为系统中的某些用户授予不同的访问级别。我希望能够授予一个用户读取访问权限,而另一个用户可以读取/写入其uid。实施这项工作需要做些什么?
我是否需要重构我的数据库以及我的JSON规则是如何构建的?
更新 - 实施新规则和数据库结构
商店01的当前数据库参考 -
database = FirebaseDatabase.getInstance().getReference("stores").child("Store 01").child("Task List"); //Find the Task List table in database and making a reference.
更新了以下规则结构
{
"rules": {
"stores": {
".read": "auth != null && (root.child('readUsers').hasChild(auth.uid) || root.child('readWriteUsers').hasChild(auth.uid))",
".write": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)"
},
"readUsers": {
".read": "auth != null && root.child('readUsers').hasChild(auth.uid)",
".write": false
},
"readWriteUsers": {
".read": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)",
".write": false
}
} }
将DB结构更新为以下内容
一种解决方案是让一些特定的数据库节点列出您的用户,如下所示:
{
"rules": {
"Store01": {
".read": "auth != null && (root.child('readUsers').hasChild(auth.uid) || root.child('readWriteUsers').hasChild(auth.uid))",
".write": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)"
},
"readUsers": {
".read": "auth != null && root.child('readUsers').hasChild(auth.uid)",
".write": false
},
"readWriteUsers": {
".read": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)",
".write": false
}
}
}
但是,使用您的数据模型会出现问题,因为您要创建多个stores
作为数据库根节点。每次创建新商店时,都需要更新安全规则!
您需要在父节点中创建这些存储,例如stores
。因此,使用新的readUsers
和readWriteUsers
节点,您的数据库将如下所示:
- task-list-for-managers
- stores
- Store01
- ....
- Store02
- ....
- readUsers
- WV0676TY67TY9: true //user Id
- PU8776TIU6543: true
- .....
- readWriteUsers
- BD563DHDV7669: true //user Id
- 87RSBE6383912: true
- .....
规则如下:
{
"rules": {
"stores": {
".read": "auth != null && (root.child('readUsers').hasChild(auth.uid) || root.child('readWriteUsers').hasChild(auth.uid))",
".write": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)"
},
"readUsers": {
".read": "auth != null && root.child('readUsers').hasChild(auth.uid)",
".write": false
},
"readWriteUsers": {
".read": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)",
".write": false
}
}
}
请注意,正如here所解释的,读写规则级联:
如果规则在特定路径上授予读取或写入权限,则它还授予对其下所有子节点的访问权限。