Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Authentication JavaScript get success

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

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);
        });

I understand that it is easy to realise whether or not authentication was unsuccessful, however, how do I know if the user was able to login with their supplied credentials? There doesn't seem to be a callback for a 'successful' log in. I currently have a login form, and I want to navigate away on a successful log in.

like image 641
BoyUnderTheMoon Avatar asked Oct 10 '16 12:10

BoyUnderTheMoon


1 Answers

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.

like image 198
Frank van Puffelen Avatar answered Oct 22 '22 00:10

Frank van Puffelen