Firebase Authentication JavaScript get success

后端 未结 3 1846
清酒与你
清酒与你 2020-12-19 08:29

With the following Firebase email authentication code, how do you know whether authentication was successful?

firebase.auth().signInWithEmailAndPassword(emai         


        
相关标签:
3条回答
  • 2020-12-19 08:30

    If nothing was cached then it was successful.

    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!
        }
    
    0 讨论(0)
  • 2020-12-19 08:33

    firebaser here

    @ksav's answer show the preferred way of detecting when a user signs in our out.

    For completeness I want to show the second way to detect this, which is in direct response to 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);
    });
    

    The then() will be invoked when the user has signed in.

    The reason we de-emphasize this approach in our documentation is that it will miss many situations. For example:

    • when a user reloads the page, the then() will not be invoked. The onAuthStateChanged() callback on the other hand will be invoked then too.
    • the a user gets signed out (for example if their short-lived token can't be refreshed), the catch() will not be invoked. The onAuthStateChanged() callback on the other hand will be invoked then too.

    If you want to explicitly respond to when the user actively signed in, the approach in my answer might be useful. But in most cases, we recommend that you that the approach in @ksav's answer.

    0 讨论(0)
  • 2020-12-19 08:46

    Get the currently signed-in user


    The recommended way to get the current user is by setting an observer on the Auth object:

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

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

    0 讨论(0)
提交回复
热议问题