Ad

How Does $uid Node Works On Firebase-realtime-database Rules?

I'm working on firebase-realtime-database on ionic, I am a bit confuse about how to "read" and "write" inside the $uid node. Which i am currently dealing with denied access.

the node looks like this

rules {
"info": {     
   "$uid": {
      ".read": true,
      ".write": "$uid === auth.uid"
   }     
 }
}

while my json database looks like this


{
  info: {
     01: {
     name:jay
     age:16
     }
  }
}


I am a bit confuse what steps to take in order to access the data inside the $uid node. I did try to update my json database node to this.


{
  info: {
    f3de4734-8fb2-42bd-971d-8e693f8aab3b: {  // auth.uid of [email protected]
            01: {
            name:jay
            age:16
            }
    }
  }
}

and my "getafdData() function" path directory to "'info/'+ getuser".

the above updates work only if the "getuser" is the owner of the file or the node that holds the data, however i want it to be read by other authenticated users as well which i can't understand with $uid.

I have already Authenticate the login using "signInWithEmailAndPassword()" function by firebase

this is the code i use to authenticate

 try {
      var r = await this.fAuth.auth.signInWithEmailAndPassword(
        "[email protected]",
        "123456"
      );
      if (r) {
        console.log("Successfully logged in!");
        await this.getafdData(); \\\ get the data when login

      }

    } catch (err) {
      console.error(err);
    }
async getafdData(){

var firebaseRef = this.afd.database.ref();
let data = await new Promise(function(resolve,reject){
   return firebaseRef.child('info/')
      .on("child_added", function(snapshot) {
         console.log(snapshot.val());
         //resolve(data);


       }, function(err) {
         console.log(err);
         reject(err);
       })
    }); 
return data;
}

Can you advise what i am doing wrong? or rather correct steps i should do in order to access the $uid node?

Ad

Answer

The ".read": true rule allow any user to read data from /info/$uidif they know the UID of the user whose data they want to read. In your code you are however attaching a listener to /info and nobody has read permission on that node, so the read is rejected.

If you want everyone to be able to read all users nodes in one go, you should move the ".read": true, rule to the /info level of your rules:

{
  "rules": {
    "info": {     
      ".read": true,
      "$uid": {
        ".write": "$uid === auth.uid"
    }     
  }
}

Actually, since you say that you want to allow reading the user info by other authenticated users, that should probably be:

{
  "rules": {
    "info": {     
      ".read": "auth != null",
      "$uid": {
        ".write": "$uid === auth.uid"
    }     
  }
}
Ad
source: stackoverflow.com
Ad