首页 > 解决方案 > firebase 数据库规则允许在特定节点上写入

问题描述

我有以下数据库:

actions : [  {
  "added" : 1535293085383,
  "countdown" : 9999999999,
  "item" : 1,
  "type" : "a"
}, {
  "added" : 1535293085383,
  "countdown" : 999999999,
  "extra" : "bb",
  "item" : "2",
  "type" : "b"
}, {
  "added" : 1635293085383,
  "countdown" : 1,
  "item" : 3,
  "type" : "c"
}]

我希望任何登录的用户都能够读取所有数据,但只能写入倒计时节点。

我的想法是每次用户读取数据时都会减少该值,但不允许他们更新任何其他节点

有我写的规则

    {
       "rules":{
          ".read":false,
          ".write":false,
          "actions":{
             ".indexOn":[
                "added"
             ],
             ".read": "auth != null",
           "countdown":{
             ".write" : "auth != null"
           }
          }
}

它拒绝从未经
身份验证的用户读取它允许从经过身份验证的用户读取它拒绝从经过身份验证的用户
写入即使在倒计时节点中

我该如何解决

标签: firebasefirebase-realtime-databasefirebase-security

解决方案


您的安全规则缺少一个级别。现在您允许写入/actions/countdown. 但是您想允许写入/actions/*/countdown. 要捕获该要求,请在规则中使用$变量:

{
   "rules":{
      ".read":false,
      ".write":false,
      "actions":{
         ".indexOn": [ "added" ],
         ".read": "auth != null",
         "$actionid": {
           "countdown":{
             ".write" : "auth != null"
           }
         }
      }
}

现在由于那里$actionidcountdown/.write规则适用于/actions.


推荐阅读