Skip to main content
 首页 » 编程设计

python之Firebase .validate 无法按预期使用 $location

2025年05月04日59yxwkf

我有以下 Firebase 规则,但我无法按预期进行验证:

{ 
  "rules": { 
    ".read": true, 
    ".write": true, 
 
    "specialItems": { 
      "$itemid": { 
        ".validate": "root.child('items/' + $itemid).exists()" 
      } 
    } 
  } 
} 

我的 .validate 规则的目的是“specialItems”列表中的条目只有在“items”列表中已经存在时才会被接受。不幸的是,无论如何 Firebase 都允许我添加到 specialItems - 毫无疑问,因为我误解了验证应该如何工作。

我正在使用应用引擎 python urlfetch API 通过 REST 与 firebase 通信,并使用 PATCH 方法。

auth_payload = {"uid": "custom:1", "auth_data": "foo"} 
token = create_token(FIREBASE_SECRET, auth_payload, {"admin": True}) 
 
url = "https:/<my-app>.firebaseio.com/specialItems.json?auth=" + token 
payload = json.dumps({"myItem": "ok"}) 
 
result = urlfetch.fetch(url=url, payload=payload, method=urlfetch.PATCH) 

当从一个空数据库开始时,这给我留下了一个完整的数据树,如下所示:

specialItems 
  -- myItem: "ok" 

我原以为这棵树无法通过验证规则。我也尝试过使用 PUT,它具有相同的效果:

url = "https://<my-app>.firebaseio.com/specialItems/myItem.json?auth=" + token 
result = urlfetch.fetch(url=url, payload='"ok"', method=urlfetch.PUT) 

另一件需要注意的事情是,我目前需要使用“admin: True”进行身份验证才能写入任何内容,尽管我的规则似乎表明任何人都应该具有读/写访问权限。让我想知道是否完全应用了我的规则 - 如果是这样,那么我不确定如何启用我的规则 - 它们就在“安全和规则” Pane 中。我还假设不允许管理员违反架构验证规则。

请您参考如下方法:

您的假设不正确。使用 admin: true 进行身份验证将绕过安全规则。因此,您的 .validate 规则将不会在这种情况下应用。 .validate 规则本身在物理上没有任何问题。

此外,假设您的问题准确反射(reflect)了实际情况,则此处不需要进行身份验证。根路径上的 .write/.read true 将允许访问 Firebase 中的任何数据。您的规则很可能运行良好并阻止了写入,这就是为什么您错误地认为您需要 admin: true 才能写入数据。

请按照 Saeed 在他的回答中建议的那样检查模拟器。