Firebase using auth.uid as key and adding rules to it and its children

Mar*_*tin 2 firebase

I have a data structure that adds user's data to their unique id such as follows.

"users" : 
    {
        "user_id":
        {
            "name":"John Doe",
            "email":"email@example.com",
            "account":"limited",
            "avatar" : "this will be a base64 data string"
        }
    }
Run Code Online (Sandbox Code Playgroud)

I want to deny users from listing other users and I also want logged in users to access their data based on their "user_id" which is gotten from auth.uid

I had tried some rules:

{
    "rules" : 
    {
        "users" : 
        {
            ".read" : "false",
            ".write" : "auth != null && !data.exists() && newData.exists() ",
            ".validate" : "newData.child('user_id').hasChildren(['name', 'email', 'account','avatar'])",
            "user_id" : 
            {
               ".read" : "auth.uid === user_id",
               ".write" : "false",
               "avatar" : 
                {
                     ".write" : "!data.exists() && newData.exists() && auth.uid === user_id",
                     ".read" : "auth.uid === user_id"
                }           
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Now keeping in mind that "user_id" can be anything and it changes per user, how can I implement that? Do you have other suggestions on a way I can work this out?

tom*_*456 8

您需要仔细查看此处的Firebase文档:https://www.firebase.com/docs/security/guide/user-security.html

您需要使用通配符路径来表示每个用户,如下所示:

{
  "rules": {
    "users": {
      "$user_id": { //this is the WILDCARD path
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

通配符路径说明:https://www.firebase.com/docs/security/api/rule/path.html

最后,我不建议以这种方式存储电子邮件,因为它无论如何都可以通过simpleLogin获得.