Firebase 安全规则确保 children 有条件

Firebase security rules ensure children conditional

我正在使用 Firebase Bolt Compiler 来构建我的安全规则,我遇到了以下情况:

以下是我使用 Bolt 构建这些规则的尝试:

type ConditionB extends Number {
  validate() = root.condition >= 5 ? this != null : this == null;
} 

type ConditionC extends Number {
  validate() = root.condition >= 10 ? this != null : this == null;
}

type Data {
  a: Number,
  b: ConditionB,
  c: ContitionC
}

path /data is Data {
  read()  = true,
  write() = true
}

下面是rules.json:

"rules": {
  "data": {
    ".validate": "newData.hasChildren(['a', 'b', 'c']),
    ...
  }
}

可以看出 .validate 规则强制所有 children 出现在 data 中。那么,根据我的条件,我如何确保 data 及其每个 children 的 .validate 规则都是正确的?

既然你的类型可以是Null,你必须扩展Number | Null 像这样:

type ConditionB extends Number | Null {
  validate() = root.condition >= 5 ? this != null : this == null;
}

type ConditionC extends Number | Null {
  validate() = root.condition >= 10 ? this != null : this == null;
}

type Data {
  a: Number,
  b: ConditionB,
  c: ConditionC
}

path /data is Data {
  read() = true;
  write() = true;
}

这导致以下 JSON 规则文件:

{
  "rules": {
    "data": {
      ".validate": "newData.hasChildren(['a'])",
      "a": {
        ".validate": "newData.isNumber()"
      },
      "b": {
        ".validate": "(newData.isNumber() || newData.val() == null) && (newData.parent().parent().child('condition').val() >= 5 ? newData.val() != null : newData.val() == null)"
      },
      "c": {
        ".validate": "(newData.isNumber() || newData.val() == null) && (newData.parent().parent().child('condition').val() >= 10 ? newData.val() != null : newData.val() == null)"
      },
      "$other": {
        ".validate": "false"
      },
      ".read": "true",
      ".write": "true"
    }
  }
}