0
votes

I try to return to the user the list of his chat with a rule. So I don't know the id of the conversations. I have tried several methods but none of them work because you have to know the chat id.

Database :

{
  "Chats" : {
    "-MPnCVZSVi5C3QbHnXl3" : {
      "messages" : [ {
        "createdAt" : 1609324431814,
        "text" : "Gggwdhj",
        "user" : "3Oi1atf8l2P4Vgsb8tZOGxpUg7q2"
      } ],
      "name" : "toto",
      "users" : {
        "3Oi1atf8l2P4Vgsb8tZOGxpUg7q2" : true
      }
    }
  }
}

Rules :

   {
      "rules": {
           
         "Chats": {
            
              ".read": "data.child('users').hasChild(auth.uid)",
              ".write": "true"
            
    
          }
      }
    }

Result : enter image description here

But when I access from the react native application. Access to chats does not pass for an authenticated user(uid : 3Oi1atf8l2P4Vgsb8tZOGxpUg7q2)

*The read failed: Error: permission_denied at /Chats: Client doesn't have permission to access the desired data.

Rules :

{
  "rules": {
     "Chats": {
        "$uid":{
          ".read": "data.child('users').hasChild(auth.uid)",
          ".write": "true"
        }

      }
  }
}

Query :

 firebase.database().ref('Chats')
        .limitToLast(20)
        .on('child_added', snapshot => {
            callback(this.parse(snapshot))
        }, function (errorObject) {
            console.log("The read failed: " + errorObject);
        });
1
You've included a picture of the JSON tree and security rules in your question. Please replace them with the actual JSON and rules as text, which you can easily get by clicking the Export JSON link in the overflow menu (⠇) of your Firebase Database console. Having these as text makes them searchable, allows us to easily use them to test with your actual data and use them in our answer and in general is just a Good Thing to do.Frank van Puffelen
In addition: please show the code of how you're reading from the database. Security rules only have meaning in combination with the code that triggers them.Frank van Puffelen

1 Answers

0
votes

If you want to apply a certain rule/set of rules to all child nodes, you can use a $ wildcard like this:

{
  "rules": {           
     "Chats": {
        "$chatId": {
           ".read": "data.child('users').hasChild(auth.uid)",
           ".write": "true"
        }            
     }
  }
}

For more on this, see the Firebase documentation on $ wildcard variables. In general I'd recommend reading the Firebase docs on security rules end-to-end as they're not that long, and a few hours spent there now will save you much more time down the line.