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.
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:
then()
will not be invoked. The onAuthStateChanged()
callback on the other hand will be invoked then too.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With