Handling account exists errors

Consider that we have enabled the One account per email address option in firebase settings. As you can see in the preceding screenshot when we tried to log in with the provider (Google) with an email that already exists in firebase with a different provider (such as Facebook), it throws the mentioned error—auth/account-exists-with-different-credentialwhich we can see in the preceding screenshot. To handle this error and complete the sign into the selected provider, the user has to sign in first to the existing provider (Facebook) and then link to the former AuthCredential (with Google ID token). After rewriting the authWithFacebook() method, this is how our code looks:

if (error.code === 'auth/account-exists-with-different-credential') {
// Step 2.
var pendingCred = error.credential;
// The provider account's email address.
var email = error.email;
// Get registered providers for this email.
firebaseApp.auth().fetchProvidersForEmail(email).then(function(providers) {
// Step 3.
// If the user has several providers,
// the first provider in the list will be the "recommended" provider to use.
if (providers[0] === 'password') {
// Asks the user his password.
// In real scenario, you should handle this asynchronously.
var password = promptUserForPassword(); // TODO: implement promptUserForPassword to open the dialog to get the user entered password.
firebaseApp.auth().signInWithEmailAndPassword(email, password).then(function(user) {
// Step 4.
return user.link(pendingCred);
}).then(function() {
// Google account successfully linked to the existing Firebase user.
});
}
})}

To know more about the list of error codes, visit https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signInWithPopup.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset