访问规则:允许基于访问规则的只读/读写访问

时间:2017-08-15 19:33:49

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

我想写一个购物清单应用,用户可以向其他用户提供只读或读写权限。

我计划数据库看起来像这样:

{
    "lists": {
        "1": {
            "title": "List #1",
            "items": [...],
            "owner": "user1",
            "read_only_access": [ {"user2": true} ],
            "read_write_access": [ {"user3": true} ],
        },
        "2": {
            "title": "List #1",
            "items": [...],
            "owner": "user1",
            "read_only_access": [ {"user3": true} ],
            "read_write_access": [],
        },
        "3": { ... }
    },
    "users": {
        "user1": {
            "name": "John",
        },
        "user2": { ... },
        "user3": { ... }
    }
}

如何定义"列表"的访问规则?树,所以:

  • 所有者将拥有对其所有列表的读写权限
  • read_only_access列表中的用户将具有读取权限
  • read_write_access列表中的用户将具有读写访问权限
  • 既不是笔记的所有者,也不是笔记的read_only_access和read_write_access列表的用户 - 甚至没有读取权限

谢谢!
斯拉维克

1 个答案:

答案 0 :(得分:0)

<强> 数据库

{
  "list-users" : {
    "1": {
      "user2" : {
        "access" : { "read" : true, "write": false }
      },
      "user3" : {
        "access" : { "read": false, "write" : true }
      }
    },
    "2": {
      "user3" : {
        "access" : { "read" : true, "write": false }
      }
    }
  },
  "lists" : {
    "1": {
      "items": [ ... ],
      "owner" : "user1",
      "title" : "List #1"
    },
    "2": {
      "items": [ ... ],
      "owner" : "user1",
      "title" : "List #2"
    },
    "3": {
      "items": [ ... ],
      "owner" : "user1",
      "title" : "List #3"
    }
  },
  "users" : {
    "user1" : { "name" : "John" },
    "user2" : { "name" : "Jane" },
    "user3" : { "name" : "Joel" }
  }
}

<强> 规则

{
  "rules": {
    "list-users": {
      "$lid": {
        "$uid": {
          ".write": "auth.uid === root.child('lists/$lid/owner').val()",
          ".validate": "newData.child('access').hasChildren(['read', 'write'])"
        }
      }
    },
    "lists": {
      "$lid": {
        ".read": "data.child('owner').val() === auth.uid || root.child('list-users').child($lid).child(auth.uid).child('/access/read').val() === true",
        ".write": "data.child('owner').val() === auth.uid || root.child('list-users').child($lid).child(auth.uid).child('access/write').val() === true"
      }
    },
    "users": {
      "$uid": {
        ".read": "auth !== null",
        ".write": "auth.uid === $uid"
      }
    }
  }
}