Firebase规则通配符和子对比

Ale*_*lex 8 real-time wildcard firebase firebase-realtime-database firebase-security-rules

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

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

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

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

输出(成功):

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

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

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

输出(失败):

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

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

Pad*_*wan 5

失败的原因是因为

root.child('die/i').val()
Run Code Online (Sandbox Code Playgroud)

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

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

以下为您提供您想要的结果

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

Firebase文档