我有以下使用 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)都已包含在内,上面的代码工作得绝对正常,唯一的问题是我无法理解它。
我的疑问如下:
- 行
authData=ref.getAuth();
执行什么操作以及执行后 authData 包含什么内容? - 在 else block 中,什么是值和快照。我根本不明白那条线。
ref.child("users").child(authData.uid).on("value", function(snapshot)
有人可以解答我的疑问吗?谢谢。
最佳答案
好的,这里是:
首先,如果您还没有更新您的 Firebase 安全规则,您应该先更新:Firebase security rules guide
ref.getAuth() 返回一个值,如果您尚未获得授权,则该值将为 null,否则它将包含一个对象,其中包含有关用户如何授权的一些信息(自定义 token 、facebook id、电子邮件)等)
这一行:
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/