我希望我的用户能够使用我的应用添加帖子
。我需要知道每个帖子是谁发布的,以便客户使用
this.firebaseapp.database().ref('posts/').push({
userId, text, timestamp:new Date()
});
从技术上讲,有人可以修改客户端并发送 userId
的任何值,因此我需要一个数据库规则来防止这种情况发生。
Firebase 网站上的用户数据示例提到:
{
"rules": {
"users": {
"$user_id": {
// grants write access to the owner of this user account
// whose uid must exactly match the key ($user_id)
".write": "$user_id === auth.uid"
}
}
}
}
我想我基本上想要 .write
限制,但由于 Posts
是一个不同的数据集,我不想使用 Post 键,我想引用传入的值。
这是我尝试过的方法,但它允许仍然编写帖子:
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"posts": {
"userId": {
".write": "newData.val() === auth.uid"
}
}
}
}
最佳答案
第一个代码片段在语法上是不正确的。但我们假设您的意思是:
this.firebaseapp.database().ref('posts/').push({
userId: userId, text: text, timestamp:new Date()
});
您想要的规则是:
{
"rules": {
".read": "auth != null",
"posts": {
"$postid": {
".write": "newData.child('userId').val() === auth.uid"
}
}
}
}
主要区别:
- 我删除了顶级
".write"
规则。权限向下级联:一旦您授予某个级别的访问权限,您就无法在较低级别取消该权限。 - 我重新添加了
$postid
,这是必需的,因为此规则需要应用于/posts
下的所有子节点。$postid
实际上只是一个允许这样做的通配符规则。 - 我现在确保您拥有对单个帖子的写入权限,因为仅对
userId
属性执行此操作将不允许用户再写入实际帖子。
关于javascript - 使用规则强制 Firebase 数据库中字段的用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45315549/