I would like to implement \"write\" security rules in Firebase depending on users roles.
My data structure is like this:
+ myapp
+ users
+ john
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.
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"
}
}
}
}
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)