如何在网络应用程序中使用Firebase进行用户授权

How the user authorization is done using Firebase in a webapp?

本文关键字:Firebase 用户 授权 网络 应用程序      更新时间:2023-09-26

我有以下使用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块中,什么是快照。我一点也不懂这句话。ref.child("users").child(authData.uid).on("value", function(snapshot)

有人能澄清我的疑虑吗?谢谢

好了:

首先,如果你还没有更新你的firebase安全规则,你应该首先更新:firebase安全规范指南

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

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

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

我希望我能为你澄清一些事情!