麻烦编写firebase写入规则以推送数据

时间:2018-07-21 16:48:18

标签: android firebase firebase-realtime-database firebase-security-rules

我正在尝试将数据推送到数据库,并且我想检查推送数据的所有者ID是否与推送数据的人的uid相同。我被拒绝了。我不知道如何编写用于推送数据的安全规则,也找不到任何相关信息。数据结构如下:

Shops{
    "Shop1PushId" : {
        "ShopCredentials" : {
        "Owner" : "ownerUID"
        }
    }
    "Shop2PushId" : {
    ...
}

这是我要推动的对象。

{
    "ShopCredentials" : {
        "Owner" : "owner_id",
        "Another" : "another thing"
    }
}

这是我的Firebase规则:

"Shops" : {
  ".read" : true,
  ".write" : "newData.child('ShopCredentials').child('Owner').val() === auth.uid"
}

android studio中的代码

DatabaseReference shopsRef = database.getReference("Shops");
shopsRef.push().child("ShopCredentials").child("Owner").setValue(shopData.getShopOwner());

1 个答案:

答案 0 :(得分:0)

现在,您正在对/Shops本身执行规则。但这是商店的列表。您要在特定商店而不是列表上执行规则。为此,您可以在规则中添加一个所谓的$变量,这表明它下面的规则适用于每个子节点:

"Shops" : {
  ".read" : true,
  "$shopid": {
    ".write" : "newData.child('ShopCredentials').child('Owner').val() === auth.uid"
  }
}

现在,任何人都可以读取所有商店(即使他们不知道特定的节目ID),但是只有知道了特定ID并指定自己为新商店的所有者,才能写商店。 / p>

我不确定您到底要在这里保护什么。如果您希望引导过程,以便人们只能创建以自己为所有者的新商店,请意识到使用这些规则,任何人仍然可以声明其知道其ID的任何商店的所有权。如果您想避免这种情况,并且只想在创建商店时允许所有权声明,请使用以下方法:

"Shops" : {
  ".read" : true,
  "$shopid": {
    "ShopCredentials": {
      "Owner": {
        ".write" : "!data.exists() && newData.val() === auth.uid"
      }
    }
  }
}
相关问题