Firebase身份验证JavaScript获得成功

时间:2016-10-10 12:37:10

标签: javascript firebase firebase-authentication

使用以下Firebase电子邮件身份验证代码,您如何知道身份验证是否成功?

firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;

            if (errorCode === 'auth/wrong-password') {
              alert('Wrong password.');
            } else {
              alert(errorMessage);         
            }

            console.log(error);
        });

我知道很容易认识到身份验证是否不成功,但是,我如何知道用户是否能够使用他们提供的凭据登录?似乎没有回复“成功”登录。我目前有一个登录表单,我想要成功登录导航。

3 个答案:

答案 0 :(得分:17)

firebaser here

@ ksav的答案显示了检测用户何时登出的首选方式。

为了完整性,我想展示第二种检测方法,即直接回复signInWithEmailAndPassword

firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
   // user signed in
}).catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;

    if (errorCode === 'auth/wrong-password') {
        alert('Wrong password.');
    } else {
        alert(errorMessage);         
    }
    console.log(error);
});

当用户登录时,将调用then()

我们在文档中不再强调这种方法的原因是它会错过很多情况。例如:

  • 当用户重新加载页面时,将不会调用then()。另一方面onAuthStateChanged()回调 也会被调用
  • 用户退出登录(例如,如果无法刷新其短期令牌),则不会调用catch()。另一方面onAuthStateChanged()回调 也会被调用

如果您想明确回复用户何时主动登录,我的回答中的方法可能会有用。但在大多数情况下,我们建议您使用@ ksav的答案。

答案 1 :(得分:6)

获取当前登录的用户

获取当前用户的推荐方法是在Auth对象上设置观察者:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

文档:https://firebase.google.com/docs/auth/web/manage-users

答案 2 :(得分:-1)

如果没有缓存任何内容,那么它就会成功。

var isSuccessful = true
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
        // Handle Errors here.
        var isSuccessful = false
        var errorCode = error.code;
        var errorMessage = error.message;

        if (errorCode === 'auth/wrong-password') {
          alert('Wrong password.');
        } else {
          alert(errorMessage);         
        }

        console.log(error);
    })
    finally {
     if(isSuccessful)
         //Success!
    }