Firebase Authentication JavaScript get success

Firebase Authentication JavaScript get success

本文关键字:success get JavaScript Authentication Firebase      更新时间:2023-09-26

使用以下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);
        });

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

firebase 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的答案中的方法。

获取当前登录的用户


获取当前用户的推荐方法是在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

如果没有缓存,则表示成功。

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!
    }