Firebase JavaScript Authentication Gets Success

Using the following Firebase email authentication code, how did you know if 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 see if authentication was unsuccessful, however, how do I know if a user was able to log in with his credentials? There does not seem to be a callback for a "successful" login. I currently have a login form and want to switch to a successful login.

+4
source share
3 answers

firebaser here

@ksav answer shows the preferred way to detect when a user signs in our case.

, 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.

+13


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

+5

, .

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

Source: https://habr.com/ru/post/1657269/


All Articles