问题
I have a database node called (people) that looks like this:
people
|
|
-------UserID1 //which is a random id
| |
| |
| ----UserId2 //which is a random id
| |
| |
| name:"some_name"
| id:"UserId2"
| image:"image_url"
|
|
|
-------UserId2
|
|
----UserId3
|
|
name:"some_name"
id:"UserId3"
image:"image_url"
If we look at the (people / UserID1 / UserId2) node :
Since UserId1 and UserId2 are 2 random ids, then if we want to write a rule to UserId2 we will notice that it is 2 random id level deep.
What I want is to write a rule at this specified path that says these:
1) people / UserId1 : can be written by (UserID1) and (UserId2).
2) people / UserId1 : can be read by (UserID1) and (UserId2).
3) people / UserId1 / UserId2 : must end up with a newData that has (name, id, image).
How do I do this?
Thanks.
回答1:
Due to the way Firebase Realtime Database rules cascade into deeper keys, allowing people/UserId1
to be writable by UserId2
is not advised, as this would allow UserId2
write access to the data of other users stored under people/UserId1
like people/UserId1/UserId3
.
But using this trait, we can "add" users that are allowed read & write permissions as we go deeper into the data structure.
So the new conditions are:
people/UserId1
- UserId1 has read & write accesspeople/UserId1/UserId2
- UserId2 has read & write accesspeople/UserId1/UserId2
- must always contain 'name', 'id' and 'image' keyspeople/UserId1/UserId3
- cannot be read/written by UserId2
{
"rules": {
"people": {
"$userId1": {
"$userId2": {
".read": "auth.uid == $userId2", // add $userId2 to those granted read permission, cascades into deeper keys
".write": "auth.uid == $userId2", // add $userId2 to those granted write permission, cascades into deeper keys
".validate": "newData.hasChildren(['name', 'id', 'image'])" // any new data must have 'name', 'id' and 'image' fields.
},
".read": "auth.uid == $userId1", // add $userId1 to those granted read permission, cascades into deeper keys
".write": "auth.uid == $userId1" // add $userId1 to those granted write permission, cascades into deeper keys
}
}
}
Lastly, if it is also required that people/UserId1/UserId2/id
is equal to UserId2
, you can change the ".validate"
rule to enforce this:
".validate": "newData.hasChildren(['name', 'id', 'image']) && newData.child('id').val() == $userId2" // any new data must have 'name', 'id' and 'image' fields and 'id' must have a value of $userId2
来源:https://stackoverflow.com/questions/49215249/firebase-how-to-write-security-rule-for-a-child-that-is-2-level-random-id-deep-i