【问题标题】:How the user authorization is done using Firebase in a webapp?如何在 webapp 中使用 Firebase 完成用户授权?
【发布时间】:2016-05-06 22:33:02
【问题描述】:

我有以下代码用于使用 Firebase 进行用户授权,但我无法理解这些代码。在代码下方,我提到了我面临的疑问。请有人澄清一下。

var ref = new Firebase("https://prj_name.firebaseio.com");
var loggedInUser = [];
$(document).ready(function() {
    authData=ref.getAuth();

    if(authData == null){
        //TODO find an elegant way to manage authorization 
    //  window.location = "../index.html";
    }else{
        ref.child("users").child(authData.uid).on("value", function(snapshot){
            $( "span.user-name").html(snapshot.val().displayName);  
            loggedInUser.displayName = snapshot.val().displayName;
        });

    }

    $("#cPassword").focusout(function() {
        validatePassword($("#cPassword"), $("#password"));
    });


    $(document).on("click", ".clickable-row" ,function(){
        window.document.location = $(this).data("href");
    });
});

function validatePassword(password, cPassword) {
    if (cPassword.val() != password.val()) {
        cPassword.css('border-color', 'red');
        password.css('border-color', 'red');
        return false;
    }
    return true;
}

所有必要的库(如 firebase)都已包含在内,上面的代码运行良好,唯一担心的是我无法理解它。

我的疑惑如下:

  1. authData=ref.getAuth(); 行有什么作用以及 authData 在执行后包含什么?
  2. 在 else 块中,valuesnapshot 是什么。我完全不明白这一行。 ref.child("users").child(authData.uid).on("value", function(snapshot)

有人可以澄清我的疑问吗?谢谢。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-authentication


    【解决方案1】:

    好的,到此为止:

    首先,如果您还没有更新您的 Firebase 安全规则:Firebase security rules guide

    1. ref.getAuth() 返回一个值,如果您尚未获得授权,则该值将为空,或者它将包含一个对象,其中包含有关用户如何获得授权的一些​​信息(自定义令牌、facebook id、电子邮件等等)

    2. 此行:ref.child("users").child(authData.uid).on("value", function(snapshot)。在这里,您基本上是从您的用户集合中请求一些数据:'/users/{some unique id}'。当您从 firebase 请求数据时,只要数据准备好使用,Firebase 就会触发“值”回调并使用此回调传递数据(快照)。

    firebase 文档非常好,我建议您通读整个网络指南。 Firebase web guide

    我希望我能够为你解决一些问题!

    【讨论】:

    • 感谢您的回答。但是仍然存在一个疑问,“价值”在功能中的作用是什么?请详细说明。
    • 当您向firebase请求数据时,只要数据准备好使用,Firebase就会触发“值”回调并使用此回调传递数据(快照)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2011-10-09
    • 2018-06-07
    • 2018-10-30
    • 1970-01-01
    相关资源
    最近更新 更多