Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Link facebook account with existing user

I have a current database with active users in Firebase that can login with user/pwd but now I'm implementing the facebook login and I realised the only way to link a facebook account with an existing user is only when the user is already logged with the user/pwd but not before the login.

I have two buttons in my app (login with fb and with email) but if I try to login with fb using the same email of an existing user, I will receive the following error auth/account-exists-with-different-credential and the documentation says that in order to fix this the user needs to login first then link.

Do you know if there is a way to link both accounts but without perform a login first, I mean, from the login view?

like image 219
SoldierCorp Avatar asked Aug 24 '17 21:08

SoldierCorp


1 Answers

You need to sign in the user first before linking. This is important if you want to ensure it is the same user. Otherwise you can switch to multiple accounts per email in the Firebase console. The way to solve this, when you get the error auth/account-exists-with-different-credential, the error will contain error.email and error.credential after you sign in with Facebook and the account already exists as a password account. You then call firebase.auth().fetchProvidersForEmail(error.email) to which resolves with the list of provider IDs for that email. In this case, it will contain ['password']. You then ask the user to provide their password. You call signInWithEmailAndPassword(error.email, password) to sign-in the original user. You then call firebase.auth().currentUser.linkWithCredential(error.credential) to link the Facebook credential to the password account. Now both accounts are merged and the user can sign in with either.

like image 73
bojeil Avatar answered Oct 13 '22 18:10

bojeil