【问题标题】:What is the proper way of storing timestamps in Firebase if we don't want them to be editable?如果我们不希望它们可编辑,那么在 Firebase 中存储时间戳的正确方法是什么?
【发布时间】:2017-08-03 09:24:40
【问题描述】:

假设我的数据库中有一个messages 节点,其结构如下:

"messages": {
  "$messageId": {
    "text": "Hello there!",
    "created_by": "$userId",
    "created_at": 1501749790029
  }
}

还有这条规则:

"messages": {
  ".read": "auth != null",
  "$messageId": {
    ".write": "auth != null",
    // required fields
    ".validate": "newData.hasChildren(['text', 'created_by', 'created_at'])"
  }    
}

看起来很标准。但我的问题是,这个结构和规则允许任何用户将created_at 的值更改为任何值,对吧? created_at 属性应该是消息推送时间的时间戳,并且不能编辑。

如果我像这样重新构建我的数据库,我是否正确:

"messages": {
  "$messageId": {
    "text": "Hello there!",
    "created_by": "$userId"
  }
},
"created_at": {
  "$messageId": 1501749790029
}

基本上,我会将created_at 移动到一个单独的节点,因此用户无法对其进行编辑。然后,我将通过 Cloud Functions 设置一个事件触发器,当有新消息推送到 messages 时,它将自动将时间戳推送到 created_at

【问题讨论】:

    标签: firebase firebase-realtime-database


    【解决方案1】:

    这样做的方法是允许设置 created_at 值仅在没有先前值的情况下,here 是文档

    "messages": {
      ".read": "auth != null",
      "$messageId": {
        ".write": "auth != null",
        // required fields
        ".validate": "newData.hasChildren(['text', 'created_by', 'created_at'])"
        "created_at": {
            ".write": "!data.exists()"
        }
      }    
    }
    

    另外,我认为您可能想要验证消息的所有者,以防止用户以其他人的身份发布:

     "created_by": {
         ".validate": "newData.val() == auth.uid"
     }
    

    【讨论】:

      【解决方案2】:

      经过进一步研究,我发现我可以在 Firebase 规则中使用 .validatenow 变量来防止无效的时间戳:

      "messages": {
        ".read": "auth != null",
        "$messageId": {
          ".write": "auth != null",
          ".validate": "newData.child('created_at').val() == now && newData.hasChildren(['text', 'created_by', 'created_at'])"
        }    
      } 
      

      这比我想的要简单。太棒了。

      【讨论】:

      • 这允许任何身份验证用户使用当前时间戳推送包含textcreated_bycreated_at 值的对象。如果您希望该字段不可编辑,这是行不通的
      猜你喜欢
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      相关资源
      最近更新 更多