javascript - 如何在 Web 应用程序中使用 Firebase 完成用户授权?

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

我有以下使用 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 block 中,什么是快照。我根本不明白那条线。 ref.child("users").child(authData.uid).on("value", function(snapshot)

有人可以解答我的疑问吗?谢谢。

最佳答案

好的,这里是:

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

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

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

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

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

关于javascript - 如何在 Web 应用程序中使用 Firebase 完成用户授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067367/

相关文章:

javascript - 创建一个返回 Promise 并处理回调的函数

ios - 'downloadURL( )' is deprecated: Use ` StorageReference.downloadURLWithCompletion()` 获取当前下载 URL。

java - 推送完后如何获取 child 的数据?

javascript - AngularJS 中的 console.log 在范围函数之后执行

javascript - 未捕获的语法错误 : Unexpected token : when returning JSON

firebase - 如何使用 FCM 为亚马逊 Kindle FireOS 实现推送通知

typescript - 类型 'accessToken' 上不存在属性 'AuthCredential'

javascript - typescript 字典有问题

javascript - Lodash 是否捆绑/包含 Underscore?

android - FirebaseAuth.AuthStateListener.onAuthStateChanged(mAuth) 未按预期工作