【问题标题】:How to prevent a node from being deleted using Firebase Database rules?如何使用 Firebase 数据库规则防止节点被删除?
【发布时间】:2021-04-03 20:48:34
【问题描述】:

我有一个 firebase 数据库,只有 3 个主要节点。这是一个聊天应用,下面是结构

chat_messages
    - chatID
        -messageID
            -message (string)
            -read (bool)
            -senderName (string)
            -senderProfilePic (string)
            -sent_by (string)(uid)
            -timestamp (string)
 
chat_room
    -chatID
        -chat_mode (string)
        -last_message (string)
        -timestamp (string)
        -members
            -uid (string)
                -email (string)
                -name (string)
                -photo (string)
                -uid (string)
                -userID (int)
                -userRole (string)

user_chatrooms
    -uid
        -chatID( string) : timestamp (string)

我设置了基本安全性,允许 readwritetrue,我收到了一封来自 firebase 的电子邮件,说我的数据库有 insecure rules

然后我重新配置数据库规则如下

{
  "rules": {
    "chat_messages":
    {
      ".read": "auth != null",
        ".write": "auth != null",
    },
    "chat_room":
    {
      ".read": "auth != null",
        ".write": "auth != null",
    },
    "user_chatrooms":
    {
      ".read": "auth != null",
        ".write": "auth != null",
    }
    
  }
}

这通过阻止对上述节点之外的任何其他内容的访问来提供额外的保护。

现在如何防止这些节点被删除?

【问题讨论】:

    标签: database firebase firebase-realtime-database database-design firebase-authentication


    【解决方案1】:

    为了防止节点被删除,您可以检查写入操作中是否提供了新数据:

    ".write": "auth !== null && newData.exist()"
    

    【讨论】:

    • 谢谢。我会查的。当我们这样做时,我会停止收到“不安全的数据库”电子邮件吗?另外,您能否解释一下您的代码中发生了什么?在我看来,您正在检查用户是否已登录以及用户在通话期间是否提供了某些数据,基本上是检查提供的通话中的数据是否不为空
    • 如果您只关心停止电子邮件,您可以通过单击 Firebase 控制台右上角的铃铛图标,然后单击右上角的设置(“警报”旁边”)。但我发现最好注意这些警告,因为它们通常意味着您的数据库容易被滥用,而您对此负责。
    • 不,我也对保护数据感兴趣,也许我的问题放错了,我想检查我的数据库是否符合 Firebase 的最低“安全数据库”标准。所以我对你的代码的理解是对的?
    • 您问“我怎样才能防止这些节点被删除?”,这是我在这里回答的。您是否将此更改应用到您的规则中,是否可以防止删除?
    • 嘿@PeakGen 这有什么更新吗?您是否有机会检查此规则是否按照您的要求阻止删除节点?