我正在 Vue JS 中建立一个新项目。我正在构建一个带有 Firebase 集成的博客。这个想法是任何登录的用户都能够创建博客文章,这些文章被保存到 Firebase 实时数据库中:https://xxx.firebaseio.com/blogs.json
,每个博客都有一个唯一的 Firebase ID。
我遇到的问题是,如果有多个用户创建博客文章,传统的 Firebase 规则规定对于登录用户,博客文章将在那个用户下创建,如果其他用户已登录,他们的博客帖子将显示在他们的用户下方。
这很好,但这意味着当我尝试对我的博客文章执行 v-for
时,我有两个对象,每个对象都针对用户,每个对象中可能有多个博客对象一个无法将这些取出来的人。
以下是我目前的规则:
{
"rules": {
"blogs": {
".read": true,
".write": false,
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
我希望能够为登录用户创建所有博客帖子,并在 blogs
而不是用户 ID 下创建帖子:$uid
,我怎样才能做到这一点?
目前,这是我根据列出的当前规则获得的输出:
{
"PvWsi3t9mFZza5gXP8qNQaCktDN2": {
"-LrZ87XS02DanBTybhij": {
"body": "<p><strong>test</strong></p>",
"creation": "",
"slug": "test",
"title": "My very first blog post"
},
"-LrZ8KjsJyGT1YFsIJ3G": {
"body": "<p><strong>jjj</strong></p>",
"creation": "2019-10-19",
"slug": "test-2",
"title": "Second post"
}
},
"yLLOq9jC5odefHBENkO3r2ztNzZ2": {
"-LrZ8ZRhLVEylBFaGcnq": {
"body": "<p>content here</p>",
"creation": "2019-10-04",
"slug": "test-two",
"title": "My very first blog post - ryan"
}
}
}
更新
这是我的 Firebase 引用,它添加了一篇博文:
firebase.database().ref('blogs/' + this.$store.state.user.uid).push(this.post).then(() => {
console.log('success')
}).catch((err) => {
console.log('error', err)
})
最佳答案
使用诸如(未测试)的规则
"rules": {
"blogs": {
".read": true,
"$blogId": {
".write": "(!data.exists() || data.child('author').val() == auth.uid)
&& (newData.child('author').val() == auth.uid || !newData.exists())"
}
}
}
您可以为您的博客使用平面结构,方法是在其中添加一个 author
字段并强制它成为创建者的 UID。
第一行“.write”表示“这是一个新博客或者是您的博客”。
第二行表示“它现在是您的博客或已被删除”。
你的代码应该是这样的
const postWithAuthor = this.post;
postWithAuthor.author = this.$store.state.user.uid;
firebase.database().ref('blogs').push(postWithAuthor).then(() => {
console.log('success');
}).catch((err) => {
console.log('error', err);
});
您担心,通过公开 UID,任何人都可以使用假 UID 并写入您的数据库。这就像说人们不应该知道你是“RyanHolton”,因为他们可以发布帖子并将它们标记为你的。
在您的规则中,newData.child('author').val() == auth.uid
确保如果有人说他们是 X,他们也被认证为 X。确实能够写入您的数据库,但他们必须为“作者”输入真实的 UID。
如果你只想允许某些人写,你应该在你的数据库中添加他们的 UID,可能在“admins”路径中,然后添加
&& root.child('admins/'+auth.uid).exists()
您的“.write”规则。
关于javascript - Firebase 只允许登录用户写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58465148/