【问题标题】:Firebase realtime database rules for single properties different as for the other properties in same object tree单个属性的 Firebase 实时数据库规则与同一对象树中的其他属性不同
【发布时间】:2017-05-03 02:11:02
【问题描述】:

我试图让我的 firebase 实时数据库规则运行正确,但单个属性规则有问题。

我的 firebase 对象看起来像这个例子

"products": {
        "KUg68BknfYWuEjAKla5": {
          "cat": "Pizzas",
          "likes": 132,
          "item_price": 39.9,
          "item_price_single": 39.9,
          "name": "Mussarela",
          "observation": "",
          "product_id": "-KUg68BknfYWuEjAKla5",
          "product_image": "massapan-mussarela.jpg",
          "quantity": 1
        }

我对这个对象的规则现在看起来像这样

  "products": {
    ".read": true,
    ".write": "root.child('users').child(auth.uid).child('admin').val() == 'user_is_admin'" 
  ".indexOn": ["status", "categoryId"]
},

所以基本上我允许每个人都可以读取对象,但只有管理员可以写入对象。我的问题是单个属性“喜欢”需要每个经过身份验证的用户都可以写入。我通常会用 ".read": "auth != null", 来做,但我不知道如何将它们组合到我的规则中。我可以用 .write 设置多行吗?我需要将它们组合成一行吗?我尝试了所有我能想到的方法,但没有成功。

提前谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以在规则中指定对特定子节点的访问权限。例如

    products
      product_0
        likes: 123
        item_price: 1.99
      product_1
        likes: 222
        item_price: 4.99
    

    只允许所有人读取点赞节点但限制写入管理员的规则看起来像这样(未经测试,但类似这样)

    {
      "rules": {
        "products": {
          "$each_product": {
            "likes": {
             ".read": true,
             ".write": "root.child('users').child(auth.uid).child('admin').val() == 'user_is_admin'"
            },
           "item_price": {
             ".read": true,
             ".write": true
           }
          }
        }
      }
    }
    

    另一方面,item_price 节点可以被所有人读写。任何人都不能访问其他子节点。

    【讨论】:

    • 明白。在这种情况下只是另一个问题。我不能结合两个不同的东西,比如 root.child('users').child(auth.uid).child('admin').val() == 'user_is_admin' || $id = = auth.id
    【解决方案2】:

    您可以创建一个喜欢该类别/项目的用户列表,而不是存储喜欢的数量。像这样的:

    likes: {
      userid_1: true,
      userid_2: true
    }
    

    这样,您可以只允许用户编辑他们的路径。就像您通常对用户列表所做的那样:

    ".write": "auth.uid === $user"
    

    真正的价值可以是任何东西,因为不喜欢内容的用户不会出现在列表中。

    您只需要计算列表中的项目数即可获得喜欢的数量。

    不,您不能有多个写入规则。相反,请使用“.validate”。读写规则级联,因此如果其中一个为真,则其他所有规则都将被忽略。验证规则不会级联,它们都需要为真

    【讨论】:

    • 谢谢,我明白了,我会在下一次更新中坚决将喜欢的产品从产品列表中删除。自从有一个移动应用程序已经在运行并且我需要为所有用户更新(加上 iTunes 批准等松散的时间)之后,我首先按照 Jay 的建议设置了规则(现在一个一个)。
    • 有趣的是您对验证的评论在这种情况下我如何使用验证而不是.write?你能给我举个例子吗?我是新手,这对我来说还是有点棘手。
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多