Firebase: set security rules depending on user roles

前端 未结 1 1394
挽巷
挽巷 2020-12-01 00:53

I would like to implement \"write\" security rules in Firebase depending on users roles.
My data structure is like this:

+ myapp
  + users
    + john
            


        
相关标签:
1条回答
  • 2020-12-01 01:27

    Based on the names of your user records, they don't match auth.uid, which is probably a Simple Login id, such as twitter:2544215.

    Start by adjusting your users to be stored by their Simple Login uid:

    + myapp
      + users
        + twitter:2544215
          + email: "john@mail.com"
          + roles
            + administrator: true
        + twitter:2544216
          + email: "mary@mail.com"
          + roles
            + moderator: true
        + ...
      + documents
        + -JVmo6wZM35ZQr0K9tJu
          + ...
        + -JVr56hVTZxlAI5AgUaS
          + ...
        + ...
    

    Next, add a security rule so that administrators can access documents. You have a couple options here, depending on your specific use case.

    1. To give administrators write access to contents of each document:

      {
        "rules": {
          "documents": {
            "$documents": {
              ".write": "root.child('users').child(auth.uid).child('roles').child('administrator').val() === true"
            }
          }
        }
      }
      
    2. Or, alternatively, give them access to the whole collection:

      {
        "rules": {
          "documents": {
            ".write": "root.child('users').child(auth.uid).child('roles').child('administrator').val() === true"
          }
        }
      }
      

    The difference between these two being the $documents variable that moves the security rule one step further into the hierarchy.

    (This was mostly just an aggregation of comments by @Kato into answer form)

    0 讨论(0)
提交回复
热议问题