【问题标题】:Getting permission_denied at /items: Client doesn't have permission to access the desired data在 /items 获取 permission_denied:客户端无权访问所需数据
【发布时间】:2019-05-06 17:28:11
【问题描述】:

我正在定义一个 firebase 规则来按 userId 读取数据。 userId 是用户创建的每条数据上的一个标志,当然也就是用户的 uid。

她的规则如下:

{
    "rules": {
      "items": {
        "$itemId": {
         ".read": "auth !== null && root.child('items/$itemId/userId').val() === auth.uid"
        }
      }
    }
}

我正在客户端访问数据,如下所示:

firebase.database().ref(`/items`)
    .once('value')
    .then(snapshot => {
      const places = []
      const data = snapshot.val();
      for (let key in data) {
        places.push({
          ...data[key],
          key: key
        });
      }
    })

我希望根据每个项目上的用户 ID 标志访问所有者的数据。

以下数据结构示例:

【问题讨论】:

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


    【解决方案1】:

    根据 Firebase 文档 rules are not filters。但是去年(2018)引入了查询规则,我认为blog postdocs更好理解这一点。

    因此,为了保持您当前的数据结构,您的规则应该更改为:

    {
        "rules": {
          "items": {
             ".read": "query.orderByChild == 'userId' && query.equalTo == auth.uid"
          }
        }
    }
    

    那么你也必须改变你的查询:

    firebase.database().ref(`/items`).orderByChild('userId').equalsTo(userId)...
    

    最后一件事,您的数据库结构似乎指向其他需求:

    • 如果您想让您的数据只能由创建它的用户访问,并且还有一个可以查看所有内容的管理员,那么更好的解决方案是对您的数据进行非规范化处理。您的数据结构将是:
    user_items: {
        uid1: {
              key1:{//full object here}
         }
    },
    items: {
        key1:{//partial item here, just name and photo, think on a list}
    },
    admins:{
        uid1:true
    }
    

    这里通过管理节点解决了管理问题,这可以与custom claimsFirebase Functions 结合使用。

    • 既然有一个 places word,也许您需要使用其他类似 geofire 的东西来表示位置

    【讨论】:

    • 感谢您的留言,它很有帮助。我在客户端添加了具有以下规则的管理树:" root.child('admins').child(auth.uid).child('isAdmin').val() == true"if(firebase.database().ref('/admins').orderByChild(currentUser.uid).equalTo(true)) 为管理员返回所有数据,但未返回数据。关于如何在客户端匹配提供的规则的数据过滤器有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2021-08-10
    • 2020-11-03
    • 2019-03-20
    • 2017-02-12
    • 2022-01-15
    相关资源
    最近更新 更多