Firebase对帖子发表评论的规则

时间:2018-09-09 16:12:32

标签: firebase firebase-realtime-database firebase-security-rules

与Facebook相似的帖子评论的火力爆发规则是什么?

有两件事: 首先,只有经过身份验证的用户才能发表评论。 其次,只有发表评论的用户才能删除评论。评论其ID的用户将保存在用户名中。 enter image description here

1 个答案:

答案 0 :(得分:0)

我强烈建议使用Firebase Bolt来编写/编译Firebase数据库安全性规则。数据结构可能变得庞大而复杂。使用Bolt language,您将能够轻松编写可用于其他数据库模式的复杂访问和结构规则。

您的规则如下所示:

path /comment/{postUid}/{commentUid} is Comment {
   read() { true }
   write() { isAuthor(this) || isAuthor(prior(this)) }
}

type Comment {
   text : String,
   username : String
}

isAuthor(value) { auth != null && value.username == auth.uid }

请注意isAuthor(prior(this))通话。这样可以确保只有作者才能删除评论。 prior函数返回当前事件(创建,更新或删除)之前保存的数据。

使用firebase-bolt工具将规则编译为JSON格式后,您将获得:

{
  "rules": {
    "comment": {
      "$postUid": {
        "$commentUid": {
          ".validate": "newData.hasChildren(['text', 'username'])",
          "text": {
            ".validate": "newData.isString()"
          },
          "username": {
            ".validate": "newData.isString()"
          },
          "$other": {
            ".validate": "false"
          },
          ".read": "true",
          ".write": "auth != null && newData.child('username').val() == auth.uid || auth != null && data.child('username').val() == auth.uid"
        }
      }
    }
  }
}