Steven Sparkies Steven Sparkies - 4 months ago 172
AngularJS Question

Firebase permission denied with security rules

This is the JSON from my data base in Firebase and I want to do some rules like the auth but I get an error and I don't know what to do:

"users" : {
"0BuRcGEZQRUaQ5T2gQf4RDUcuZE2" : {
"address" : "La Prensa",
"email" : "ougishura_5421@hotmail.com",
"id" : "0BuRcGEZQRUaQ5T2gQf4RDUcuZE2",
"lastName" : "Vega",
"middleName" : "Paul",
"name" : "Christian",
"nroDocument" : "171645220",
"phoneNumber" : "1234567890",
"rol" : "administrador",
"secondLastName" : "Niama"
}
}


These are the rules that I'm using:

{
"rules": {
"users": {
"$user_id": {
".read": "auth != null",
".write": "auth.uid === $user_id"
}
}
}
}


error:


angular.js:13550 Error: permission_denied at /users: Client doesn't have permission to access the desired data.


This is the error that I get in my web app. I can't see the users that I have registered. But when I stop using
$user_id
it works. I think that variable doesn't get my value.

code:

resultUsers : function () {
var ref = pharmacyFactory.ref.child("users");
var result = $firebaseArray(ref);
return result;
},

Answer

The problem is that you are using $firebaseArray(ref) to keep track of the whole /users branch but you are placing your read rules inside /users/user_id. Therefore, since you don't have a read rule in /users it will set the default that is false.

If you want users to have read access to the whole /users branch but write only to his own user data you might be interested in doing the following:

{
  "rules": {
      "users": {
        ".read": "auth != null",
        "$user_id": {
          ".write": "auth.uid === $user_id"
        }
      }
   }
}

If you want the user to only see his own user then you should be using $firebaseObject(ref.child(userId)) instead of $firebaseArray. And working with your rules like the following:

{
  "rules": {
      "users": {
        "$user_id": {
          ".read": "auth.uid === $user_id",
          ".write": "auth.uid === $user_id"
        }
      }
   }
}
Comments