创建新用户时出现firebase权限错误

时间:2018-03-10 21:15:59

标签: firebase firebase-realtime-database firebase-security

我正在尝试确保firebase数据库的安全性。我的问题是限制用户配置文件,以便只有用户可以编辑他/她自己的节点。当用户注册时,我创建了一个firebase auth用户,并立即通过电子邮件将此用户添加到我的数据库中;但是,在尝试向数据库添加新用户时,我收到权限被拒绝错误。

我感到困惑,因为我在firebase模拟器中的模拟运行顺利;但是,我的代码没有按预期工作。在调试中,我尝试在写入数据库时​​打印当前的uid,并将其与用户的authID进行比较,然后匹配。在另一个步骤中,我将规则简化为:auth != null,它也失败了。这让我相信用户没有及时进行身份验证,但如果是这样的话,当前uid的打印将无效。

以下是我的规则:

"users" : {
    "$user_id": {
        ".read":"true",
        ".write":"auth != null",
        ".validate": "newData.exists()",
        "isAdmin": {
          ".validate":"false"
        },
        "email": {
          ".validate":"newData.val().matches(/^.+@.+\\..+$/)"
        }
     }
}

以下是我的chrome检查器控制台的图片,用于显示错误之前的错误以及uid的打印:

enter image description here

以下是我用来编写的代码:

    var firstName =         $(".signUpForm #firstName").val();
    var lastName =          $(".signUpForm #lastName").val();
    var emailInput =        $("#emailInput").val();
    var password =          $("#passwordInput").val();
    var passwordConfirm =   $(".signUpForm #passwordConfirmInput").val();

    const promise = firebase.auth().createUserWithEmailAndPassword(emailInput, password).then(function(user) {
        console.log(user.uid);

        console.log(firebase.auth().currentUser.uid);

       // user signed in
        var usersRef = firebase.database().ref('users');
        var uid = firebase.auth().currentUser.uid;
        usersRef.child(uid).set({
            email: emailInput
        }).catch(function(error) {
            displayErrorMessage(error.code);
        }).then(function() {
            //window.location.reload(true);         
        })   
        // $(".logInMessage").html('SignedUp!');
        // $(".logInMessage").css("color", "green");

    }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password') {
            $(".logInMessage").html('Wrong password.');
            $(".logInMessage").css("color", "red");

        } else {
            $(".logInMessage").css("color", "red");                                 
            $(".logInMessage").html(errorMessage);  
        }
        console.log(error);
    });

1 个答案:

答案 0 :(得分:0)

限制用户以便他们只能编辑自己的节点可以通过以下方式完成:

".write": "auth != null && auth.uid == $user_id"

对于写访问的其他问题,您可能需要在模拟器中进行试验,或者尝试删除一些规则并缩小范围,直到您可以隔离违规行。

相关问题