uksz
uksz

Reputation: 18699

Firebase security write rule of child based on user existence

Here is my security structure so far:

{
    "rules":
    {
        "users":
        {
            "$user":
            {
                ".read": true,
                "Age":
                {
                    ".write": "$user === auth.uid",
                    ".validate": "newData.isNumber()"
                },
                "Name":
                {
                    ".write": "$user === auth.uid",
                    ".validate": "newData.isString()"
                },
                "friends":
                {
                    "$friend":
                    {
                        "Age":
                        {
                            ".write": "$user === auth.uid || $friend === auth.uid",
                            ".validate": "newData.isString()"
                        },
                        "Name":
                        {
                            ".write": "$user === auth.uid || $friend === auth.uid",
                            ".validate": "newData.isNumber()"
                        }
                    } 
                }
            }
        }
    }
}

Now, when I am trying to write to '$user' to Users, I have following error:

Attempt to write Success({"42":{"Age":42,"Name":"Nick","friends":{"11":{"Age":11,"Name":"Rob"}}}}) to /users with auth=Success({"id":42,"provider":"anonymous","uid":"anonymous:42"})
/
/users

No .write rule allowed the operation.
Write was denied.

When I set .write rule to users, then all write rules will be overwritten. I need to specify that all characteristics of $user can be written by $user only, but $friend can be written by $friend and $user. When I push users, I push them with friends, but then I will need the Friends to be able to change the their data at different users paths. Do you have any ideas?

Upvotes: 0

Views: 128

Answers (1)

uksz
uksz

Reputation: 18699

Alright, so I played with rules little bit and decided to put write rules of child's into validation, and it works just great. Here is my final code:

 {
"rules":
{
    "users":
    {
        "$user":
        {
            ".read": true,
            ".write": "$user === auth.uid",
            "Age":
            {
                ".validate": "newData.isNumber()"
            },
            "Name":
            {
                ".validate": "newData.isString()"
            },
            "friends":
            {
                "$friend":
                {
                    "Age":
                    {
                        ".validate": "newData.isString() && ($user === auth.uid || $friend === auth.uid)"
                    },
                    "Name":
                    {
                        ".validate": "newData.isNumber() && ($user === auth.uid || $friend === auth.uid)"
                    }
                } 
            }
        }
    }
}
}

Upvotes: 1

Related Questions