With the following Firebase email authentication code, how do you know whether authentication was successful?
firebase.auth().signInWithEmailAndPassword(emai
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!
}
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.
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