Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

Firebase rules realtime database

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);
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...