Javascript 使用规则强制Firebase数据库中字段的用户id
我希望我的用户能够使用我的应用程序添加Javascript 使用规则强制Firebase数据库中字段的用户id,javascript,firebase,firebase-realtime-database,firebase-security,Javascript,Firebase,Firebase Realtime Database,Firebase Security,我希望我的用户能够使用我的应用程序添加帖子。我需要知道是谁写的每篇文章,以便客户使用 this.firebaseapp.database().ref('posts/').push({ userId, text, timestamp:new Date() }); 不过,从技术上讲,有人可以修改客户端并发送userId的任何值,因此我需要一个数据库规则来防止这种情况 Firebase站点上的用户数据示例提到: { "rules": { "users": {
帖子
。我需要知道是谁写的每篇文章,以便客户使用
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