问题
I'm trying to create a password protected chat room and found this SO answer to user as an example:
Firebase: approach to storing room passwords
The problem is, given the ruleset in the answer, I can't figure out how to push new data. My rules looks like this:
{
"rules": {
"myApp":{
"chatRooms" : {
"$roomID" : {
"password": {
".read": "false",
".write": "root.child('myApp/chatRooms/' + $roomID + 'chatInfo').child('admin').val() == auth.uid"
},
"chatInfo" : {
".read":true,
".write": "data.child('admin').val() === auth.uid"
},
"members" : {
"$user_id" : {
".validate": "$user_id == auth.uid && newData.val() == root.child('feeds/chatRooms/' + $roomID + '/password').val()"
}
},
"messages" : {
".read" : "root.child('feeds/chatRooms/' + $roomID + '/members/' + auth.uid).exists()"
}
}
}
}
}
}
So now I need to be able to push a new chatRoom. But if I call this:
var obj = {
password: "test",
chatInfo : {admin: this.state.currentUser.uid, chatName: "foobar"}
};
firebase.database().ref(`myApp/chatRooms`).push(obj);
It fails because I don't have write rules to push to chatRooms/$uid. If I do this.
What is the correct way to push new data with rules like this?
回答1:
For this to work you have to write to the path(s) were your rules are.
To do that you will have to split up your push()
into two parts: generating the key and actually writing the data:
// Generate the key (this happens client side)
var key = firebase.database().ref(`myApp/chatRooms`).push().key;
// Use the key to write your data
firebase.database().ref(`myApp/chatRooms`).child(key).child('chatInfo').set({admin: this.state.currentUser.uid, chatName: "foobar"});
firebase.database().ref(`myApp/chatRooms`).child(key).child('password').set("test");
来源:https://stackoverflow.com/questions/51210591/firebase-cant-push-data-given-the-ruleset