Firebase can't push data given the ruleset

徘徊边缘 提交于 2019-12-24 18:54:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!