Firebase - 从端点获取我具有读取权限的项目

Firebase - Get items I have read access to from endpoint

TLDR:如何设置数据库访问规则,以便我可以从给定端点读取我有权访问的所有项目?

我的 Firebase 数据库中有一组类似的数据:

"employees" : [ {
    "first_name" : "Constance",
    "last_name" : "Smith",
    "createdBy: "vdBoGzI2i9f12er6ZcPjG9AiTip2"
  }, {
    "first_name" : "Agatha",
    "last_name" : "Carlton",
    "createdBy: "Tpg1mFR99meDV2QGT44pU6y7s1T2"
  },
  ...
}

我还有一个应用用户列表:

  "users" : {
    "Tpg1mFR99meDV2QGT44pU6y7s1T2" : {
      "name" : "Alex Lund",
      "isAdmin": true
    },
    "vdBoGzI2i9f12er6ZcPjG9AiTip2" : {
      "name" : "David Peterson",
      "isAdmin": false
    },
    ...
  },

基本用户将只能访问他们创建的员工;管理员将能够阅读所有内容。

{
  "rules": {
    ".write": "auth != null",
    "employees": {
      "$employee": {
        ".read": "root.child('users').child(auth.uid).child('isAdmin').val() === true || data.child('createdBy').val() === auth.uid" 
      }
    },
}

使用此规则,管理员将能够读取 ref.child('/employees/0'),但无法访问 ref.child('employees')

我怎样才能获得我拥有读取权限的所有员工? 运行 查询是唯一的解决方案吗?

使用您现在拥有的规则,对 /users 的查询将不起作用。由于您没有 /employees 的读取权限,该位置的任何侦听器都将立即被拒绝。

您可能希望规则是这样的:

{
  "rules": {
    ".write": "auth != null",
    "employees": {
      ".read": "root.child('users').child(auth.uid).child('isAdmin').val() === true"
      "$employee": {
        ".read": "data.child('createdBy').val() === auth.uid" 
      }
    },
}

使用这些规则管理员可以读取(并因此查询)/users,而普通用户只能访问他们创建的子项。

这是涉及 Firebase 数据库安全规则的常见陷阱,通常称为 "rules are not filters"。见相关section in the documentation, this original Q&A on it and any of the questions in this list.