所以,
首先:在规则中,您有三个标准参数:“read”、“write”和“validate”。您可以构建规则以适合您的数据库模式。让我们去做吧:
{
"rules":{
"Messages":{
// we will ad rules here leter
},
"Users":{
// we will ad rules here leter
},
".write":false,
".read":false
}
}
现在我们可以为“消息”节点设置不同的规则,为“用户”节点设置不同的规则。最后一个参数用于root,我们不希望用户设置新节点或读取它们,我们只想允许它们在上两个节点中读取/写入。
当用户尝试从消息节点读取时,规则将检查“根/消息”并在那里查找规则,“用户”块中的规则不会影响此操作。
规则级联工作,这意味着如果用户找到允许他写的规则,写操作将被数据库接受,即使较低的规则将禁止这个。
在 firebase 规则中,您可以使用很多功能。首先让我们保护“用户”节点。
为了允许只为经过身份验证的用户写入,我们将添加如下内容:
"Users":{
$uid:{
".write": auith.uid == $uid,
".read": auth != null,
},
".write": auth != null
}
使用 $ 符号我们可以创建变量,当用户尝试在 Root/Users/1234 中写入/读取时,$uid 将采用值 1234。使用“auith.uid == $uid”我们只允许用户在他们的自己的节点
.我们还应该将写入规则设置得较低(在“用户”节点中),以允许用户向该节点添加新的子节点。
对于“消息”规则,我们将使用 hasChild() 方法,如下所示:
"Message":{
$messageUID:{
".write": data.child('uId').val() == auth.uid,
".validate": newData.hasChild('message') && newData.hasChild('name')..
},
".write":root.child("Users").haschild(auth.uid),
".read":root.child("Users").haschild(auth.uid)
}
这里我们设置只有 uid 在 uId 属性中的用户才能写入 $messageUID 节点。 “.validate”规则检查操作后的数据是否有消息子和名称子(您可以添加更多子)。
规则 ".write":root.child("Users").haschild(auth.uid) 将只允许为用户节点中存在 id 的用户写入。
我们共同拥有:
{
"rules":{
"Messages":{
"$messageUID":{
".write": "data.child('uId').val() == auth.uid",
".validate": "newData.hasChild('message') &&
newData.hasChild('name')"
},
".write": "root.child('Users').hasChild(auth.uid)",
".read":"root.child('Users').hasChild(auth.uid)",
},
"Users":{
"$uid":{
".write": "auth.uid == $uid",
".read": "auth != null",
},
".write": "auth != null"
},
".write":false,
".read":false
}
}
我没有测试过这个规则,所以也许你需要改变一些东西,但现在你应该更好地理解如何使用规则以及你可以用它们做什么。询问是否会出错