【问题标题】:Firebase Rules - Allow .update() Only on Certain FieldsFirebase 规则 - 仅在某些字段上允许 .update()
【发布时间】:2017-10-08 04:54:50
【问题描述】:

假设我有一个这样的用户集合:

users{
    userId1234 : {
        name: "Joe",
        interests: "Programming",
        score: 1337
    }
}

是否可以编写允许的规则

let user = {name:"Joey",interests:"Code"};
db.ref("users/").child("userId1234").update(user);

但不允许:

let user = {name:"Joey",interests:"Code",score:9000};
db.ref("users/").child("userId1234").update(user);

本质上,我想保护某个字段不被写入(本例中的分数)。我知道我可以选择将该字段移到另一个集合中,但如果可能的话,我希望能够这样做。

以下是迄今为止我尝试过但没有奏效的方法:

"users":{
        ".write":"auth!=null",
        "$userId":{
          "score":{".write":false},
          "$otherFields":{".write":"auth != null"}
        }
}

^这会阻止对 /users/userId/score 的写入,但不会阻止 /users/userId 使用包含 score 属性的对象。

"users":{
        ".write":"false",
        "$userId":{
          "score":{".write":false},
          "$otherFields":{".write":"auth != null"}
        }
}         

^这允许我正确写入字段,但完全阻止 .update()。

谢谢! -乔

【问题讨论】:

  • 嗨乔。您应该将您的解决方案作为答案发布,而不是将其直接包含在您的帖子中。 Self answer 实际上在 Stack Overflow 中受到鼓励。干杯! :)
  • 知道了。谢谢@AL。 :D

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


【解决方案1】:

我的解决方案

"users":{
        "$userId":{
          ".write":"auth!=null",
          ".validate":"newData.child('score').val()
                       ===data.child('score').val()",
          "score":{".write":false},
          "$otherFields":{".write":"auth != null"}
        }
}  

".validate": "!newData.hasChildren(['score'])" 不起作用,因为“newData”实际上是更新数据的未来合并结果,而不是发布的原始数据,如果你已经有分数了,它会失败。

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2020-08-17
    • 2020-09-18
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多