通过Firebase电子邮件/密码登录

时间:2013-05-03 23:02:54

标签: firebase authentication

我正在尝试使用Firebase通过电子邮件/密码注册构建基本的Web应用程序,并进行用户身份验证。

我的设置现在包含一个main.js文件,该文件包含以下内容:

var dbRef = new Firebase('https://url.firebaseIO.com');
var authClient = new FirebaseAuthClient(dbRef, function(error, user) {
  if (error) {
    // an error occurred while attempting login
    console.log(error);
  } else if (user) {
    // user authenticated with Firebase
    console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
  } else {
    // user is logged out
    console.log('logged out!');
  }
});
function next(){
   window.location = 'index.html';
}
function test(){
     authClient.login('password', {
     email: email,
     password: password,
     rememberMe: true
    },next());
    // window.location = 'index.html';
}

我从表单和登录中获取电子邮件/密码值。这样可行。但是,只要我包含一个回调函数,然后将它们重定向到一个新的经过身份验证的页面,它就不再有效。事实上,大多数时候我都会收到“UNKOWN ERROR”回复。

当我到达下一页时,我不再登录。如果我删除next()函数并保持在同一页面上,它就可以工作 - 即使我然后从控制台触发下一个函数。你应该采用不同的方式进入另一个页面吗?

我很确定存在某种通信问题(可能登录在页面切换之前没有返回?)因为如果我在下一个函数之前添加1s超时,那么它就可以了。但这肯定不是最佳做法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

https://www.firebase.com/docs/security/simple-login-email-password.htmlauthClient.login()方法实际上并不接受回调,因此您看到的问题可能是在返回回调之前导航离开当前页面的结果,就像您一样建议。

我建议在auth客户端实例化期间传递的回调中进行重定向。 (new FirebaseAuthClient(ref, callback))并在您检测到已登录用户时重定向。在使用用户的当前身份验证状态进行实例化时,将调用此回调一次,然后在用户的身份验证状态发生更改时(例如登录或注销时)再次调用此回调。