在 Firebase 中忽略验证 id 存在

Validate id exists ignored in Firebase

我正在使用 Firebase 添加用户。我还有一个 Newuser,它是一个空用户,可以使用 id 进行初始化(id 来自我已经制作的标签)。

现在当 newuser 被初始化时,Firebase 应该检查给定的 tagid 是否已经在用户 table 中使用(作为键)。

这是我的 UsersNewUser 数据的样子;

这是我正在应用的 Firebase 规则它在模拟器中工作

{
  "rules": {
    ".read": true,
    ".write": true,
    "newuser": {
      "tagid": {
        ".validate": "root.child('users/'+newData.val()).val() === null"
      }
    }
  }
}

但出于某种原因,我能够使用 Firebase REST API 使用现有的 tagid 添加此新用户记录。 (与邮递员)

您配置的规则与您正在使用的数据库结构不完全匹配,因此您需要尝试更像:

{
  "rules": {
    ".read": true,
    ".write": true,
    "newuser": {
      "$pushid" : {
        ".validate": "root.child('users/'+newData.child('tagid').val()).val() === null"
      }
    }
  }
}

在上面的规则中,$pushid值会匹配/newuser/$pushid处的任意key(比如你的-KxhGb7zZy8cZM5Pkntz的key),然后使用newData.child('tagid')会从该新数据中获取 tagid 值。

在规则中使用$location值就像一个通配符变量,所以它会自动匹配该位置的任何节点名称。来自 $location rules documentation:

A variable that can be used to reference the key of a $location that was used earlier in a rule structure.

When you have a $location in your rules structure, you can use a matching $ variable within your rule expression to get the name of the actual child being read or written.

这是您当前结构所必需的,因为当您添加到 newuser 节点时,您的有效负载看起来像这样:

{
    "newuser" {
        "$pushId": {
            "tagid": int
        }
    }
}

您可以在 Rules Simulator in the Firebase database console 中测试您的规则。在我对此的测试中,当我在数据库中已经有 /users/1 并且我的有效负载包含 tagid: 1:

的值时,写入被拒绝