Reputation: 1
I'm working on an android project where users will be able to add a POJO to their own node in Firebase but only if the user has admin privileges.
In my Firebase database, I have the rules set up like this
"userAddedCars":{
"$uid":{
".read" : "$uid == auth.uid",
".write" : "$uid == auth.uid && root.child('users').child(auth.uid).child('admin').val() == true"
}
}
A typical user node looks like this:
root{
"users"{
"0MFmZkhIPAP4ccrdfY5F4uiCrNB3" : {
"admin" : true,
"email" : "[email protected]"
}
}
}
I have tested with the rule $uid == auth.uid
and it works as intended i.e. only able to write into their personal node. However when paired with this rule root.child('users').child(auth.uid).child('admin').val() == true
it seems as if auth.uid
doesn't get the correct UID because it doesn't work as intended, although if I hard code the UID it starts working again.
I am not sure why auth.uid
works some of the times but not always.
Code used to add POJOS
mRef = mRef.child("userAddedCars").child(UID);
mRef.child("car1").setValue(nCar);
Upvotes: 0
Views: 675
Reputation: 189
Its a bit unclear on what you are trying to accomplish from the question so here is my assumption and the accompanying solution
Assumption 1:
You have set of Users who are either admins or not and they each have a set of used cars that are privately listed. While a user can see all the cars that are added to his/her private userAddedCars list they can only Add/Update/Modify them if they have admin privileges enabled.
PS: user is always authenticated
Solution
Your current rule set is right and it will work.
auth.uid
is the UID of the currently authenticated user on the client device and in-relation to the above example data-set you will be able to execute your setValue
code successfully if your login UID has admin property set to true under users node just like user 0MFmZkhIPAP4ccrdfY5F4uiCrNB3
.
if this is where you are failing you would have to elaborate on the situation with where its working and where its not working and the data-sets used to debug the issue further.
Assumption 2:
You have set of Users who can be sometimes admins although all of them have a set of used cars that are privately listed. While a user can see and edit all the cars that are added to his/her private userAddedCars list, but if user is admin then he can Add/Update/Modify cars for other users as well...
PS: user is always authenticated
Solution
Use the below rule set
{
"rules": {
"userAddedCars": {
"$uid": {
".read": "$uid == auth.uid",
".write": "$uid == auth.uid || root.child('users').child(auth.uid).child('admin').val() == true"
}
}
}
}
Upvotes: 1