Firebase只允许创建者发布

时间:2017-07-21 14:43:53

标签: javascript firebase firebase-realtime-database firebase-authentication firebase-security

我一直在为我的个人网站开发博客应用程序,我想只允许自己发布新的博客帖子,但允许所有登录用户在帖子中添加评论。

目前,数据如下所示:

"posts": {
  "-KpZlH9PYs7mAf8avBmI" : {
    "comments" : {
      "-KpZwWIrbM3JQ2ug1c5_" : {
        "message" : "How are you today?",
        "timestamp" : 1500637173055,
        "user" : "Florin Pop"
      },
      "-KpZyxoC0OTxnDZymP-M" : {
        "message" : "I'm fine, thank you!",
        "timestamp" : 1500637814102,
        "user" : "Florin Pop"
      }
    },
    "likes" : 0,
    "text" : "asxszx",
    "timestamp" : 1500634227427,
    "title" : "qwqew"
  }
}

正如您所看到的帖子有:评论列表文字时间戳和的标题

我不确定结构是否符合我的要求。

我可以检查当前登录的用户是否只允许创建新帖子吗?

我应该单独提出意见吗?

P.S。

目前我的数据库规则是:

{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}

2 个答案:

答案 0 :(得分:1)

  

我应该单独提出意见吗?

即使不知道应用程序的所有细节,答案几乎肯定是“是”。在不同的顶级节点中使用不同的实体类型通常会大大简化数据库的安全规则。

  

我可以检查我是否是当前登录的用户。

在安全规则中,您可以检查操作是否来自具有auth != null a 身份验证用户。但是就我所见,你的JSON不包含任何UID,因此我不清楚 当前用户是谁。

答案 1 :(得分:1)

我建议你做出以下改动:

在数据库的根目录中创建一个新对象admins,即可以编辑/创建帖子的用户:

"admins": {
    "<ADMIN_1_UID>": "true",
    "<ADMIN_2_UID>": "true"
}

然后更改您的安全规则:

"rules": {
    "admins": {
        ".read": false,
        ".write": false /*This ensures that only from firebase console you can add data to this object*/
    },
    "posts": {
        ".read": true,
        ".write": "root.child('admins').child(auth.uid).val()" /*This ensures only admin can write post stuff*/
        "$postId": {
            "comments": {
                ".write": "auth != null" /*This overrides the above write rule and allow authenticated users to post comments*/
            }
        }
    }
}