【问题标题】:Firebase: How to structure public/private user dataFirebase:如何构建公共/私人用户数据
【发布时间】:2019-01-01 14:10:42
【问题描述】:

当然,我数据库中的用户拥有可以公开访问的信息以及只有他们应该看到的其他信息。我正在考虑两种不同的实现方式。

选项 1:/users/$uid 只能由该用户读取,并且让 /users/$uid/profile 可供任何人读取。

选项 2: 保持 /users/$uid 只能由该用户读取,并拥有一个公开的 /profiles/$uid。这遵循了更扁平数据结构的建议,但我看不出在这种情况下它有什么更好的地方。

【问题讨论】:

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


    【解决方案1】:

    了解“更扁平”结构为何更好的最简单方法是查看如何保护它以及如何实现功能。

    你的第一个结构是:

    users: {
      uidOfJacob: {
        stackId: 884522,
        ssn: "999-99-9999",
        profile: {
          displayName: "Jacob Philips"
        }
    
      },
      uidOfPuf: {
        stackId: 209103,
        ssn: "999-99-9999",
        profile: {
          displayName: "Frank van Puffelen"
        }
      }
    }
    

    您可以通过以下方式保护它:

    {
      "rules": {
        "users": {
          "$uid": {
            ".read": "auth.uid == $uid",
            ".write": "auth.uid == $uid"
            "profile": {
              ".read": true
            }
          }
        }
      }
    }
    

    拥有公开信息的主要原因之一是能够显示该信息的列表。在 JavaScript 中:

    ref.child('users').child(???).child('profile').on('child_added'...
    

    这行不通,因为我们在??? 中输入了什么。 Firebase 操作需要能够从一个位置读取整个列表,并且用户需要对该整个位置(而不仅仅是单个子节点)具有读取权限。

    如果我们构造数据以将公共信息与私人信息分开,我们会得到:

    users: {
      uidOfJacob: {
        stackId: 884522,
        ssn: "999-99-9999",
        profile: {
          displayName: "Jacob Philips"
        }
    
      },
      uidOfPuf: {
        stackId: 209103,
        ssn: "999-99-9999",
        profile: {
          displayName: "Frank van Puffelen"
        }
      }
    },
    "profile": {
      uidOfJacob: {
        displayName: "Jacob Philips"
      },
      uidOfPuf: {
        displayName: "Frank van Puffelen"
      }
    }
    

    您可以通过以下方式保护它:

    {
      "rules": {
        "users": {
          "$uid": {
            ".read": "auth.uid == $uid",
            ".write": "auth.uid == $uid"
          }
        },
        "profiles": {
          ".read": true,
          "$uid": {
            ".write": "auth.uid == $uid"
          }
        }
      }
    }
    

    现在要获取公开用户配置文件的列表,您可以:

    ref.child('profiles').on('child_added'...
    

    这会起作用,因为每个人都拥有profiles 的读取权限。

    【讨论】:

    • 我当前的用例是在用户 ID 已知的情况下查看配置文件信息,这就是为什么我很难看到差异的原因。更嵌套的方法会阻止获取配置文件列表,这可能会在以后派上用场。
    • 这基本上意味着新用户注册后需要在数据库中写入两次:1.“users”节点的新条目(uid及其子节点),2.“profile”的新条目节点(带有 displayName 子节点的 uid)? @FrankVanPuffelen
    • @Ewoks 是的,没错。 Frank 的方法在 NoSQL 数据库设计中很常见,其中读取性能的提高是以降低写入性能为代价的。
    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多