Firebase规则通配符和子对比

问题描述 投票:8回答:1

我正在尝试将Firebase的Rule通配符与子项比较混合使用。

我正在读一个价值为'4'的孩子。

当我进行文字比较时,模拟器会给我绿灯(如下所示):

{
  "rules": {
    "die": {
      "rolls": {
        "$i": {
          ".read": "4 == root.child('die/i').val()"
        }
      },
      "i": {
        ".read": true,
        ".write": true
      }
    }
  }
}

输出(成功):

Type    read
Location    /die/rolls/4
Data    null
Auth    null
Read successful
Line 7 (/die/rolls/4)
read: "4 == root.child('die/i').val()"

但是通配符比较失败了。为什么?

{
  "rules": {
    "die": {
      "rolls": {
        "$i": {
          ".read": "$i == root.child('die/i').val()"
        }
      },
      "i": {
        ".read": true,
        ".write": true
      }
    }
  }
}

输出(失败):

Type    read
Location    /die/rolls/4
Data    null
Auth    null
Read denied
Line 7 (/die/rolls/4)
read: "$i == root.child('die/i').val()"

(另外,我试过模拟身份验证;同样的事情。)

firebase firebase-realtime-database real-time wildcard firebase-security-rules
1个回答
2
投票

这是失败的原因是因为

root.child('die/i').val()

返回一个数字。根据firebase文档

注意:路径键始终是字符串。因此,请务必记住,当我们尝试将$变量与数字进行比较时,这将始终失败。这可以通过将数字转换为字符串来纠正(例如$ key === newData.val()+'')

以下为您提供所需的结果

 {
 "rules": {
   "die": {
     "rolls": {
       "$i": {
         ".read": "$i === root.child('die/i').val()+''"
       }
     },
     "i": {
       ".read": true,
       ".write": true
     }
   }
 }
}

Firebase documentation

© www.soinside.com 2019 - 2024. All rights reserved.