且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何授予从Firebase身份验证和数据库对特定UID的读/写访问权限

更新时间:2021-07-14 21:46:21

一种解决方案是让一些特定的数据库节点列出您的用户,如下所示:

One solution is to have some specific database nodes listing your users, as follows:

{
  "rules": {

    "Store01": {
            ".read": "auth != null && (root.child('readUsers').hasChild(auth.uid) || root.child('readWriteUsers').hasChild(auth.uid))",
            ".write": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)"
      },

    "readUsers": {
            ".read": "auth != null && root.child('readUsers').hasChild(auth.uid)",
            ".write": false   
    },


    "readWriteUsers": {
            ".read": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)",
            ".write": false   
    }

  }
}

但是,对于您的数据模型,将会出现问题,因为您要创建多个stores作为数据库根节点.每次创建新商店时,都需要更新安全规则!

However, with your data model, there will be a problem because you are creating multiple stores as database root nodes. Each time you create a new store you would need to update the security rules!

您需要在父节点中创建这些存储,例如stores.因此,使用新的readUsersreadWriteUsers节点,您的数据库将如下所示:

You need to create these stores in a parent node, e.g. stores. Therefore, with the new readUsers and readWriteUsers nodes, your database would look like the following:

- task-list-for-managers
   - stores
     - Store01
        - ....  
     - Store02
        - ....    
   - readUsers
     - WV0676TY67TY9: true   //user Id
     - PU8776TIU6543: true   
     - .....
   - readWriteUsers
     - BD563DHDV7669: true   //user Id
     - 87RSBE6383912: true   
     - .....

规则如下:

{
  "rules": {

    "stores": {
            ".read": "auth != null && (root.child('readUsers').hasChild(auth.uid) || root.child('readWriteUsers').hasChild(auth.uid))",
            ".write": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)"
      },

    "readUsers": {
            ".read": "auth != null && root.child('readUsers').hasChild(auth.uid)",
            ".write": false   
    },


    "readWriteUsers": {
            ".read": "auth != null && root.child('readWriteUsers').hasChild(auth.uid)",
            ".write": false   
    }

  }
}

请注意,如此处所述,请阅读并编写规则级联:

Note that, as explained here, read and write Rules cascade:

如果规则授予对特定路径的读取或写入权限,则 它还授予对其下所有子节点的访问权限.

If a rule grants read or write permissions at a particular path, then it also grants access to all child nodes under it.