Frostless
Frostless

Reputation: 848

How to correctly link different Auth accounts in Firebase IOS

Background:

I am developing an IOS app using firebase as backend. There are 3 authentication: 1:password and email 2:FaceBook 3:Google

I have checked the option "one email per account" option.

The situation is:

Say if I first sign in with one of the Auth provider and later, log out, and want to sign up with any other two Auth providers. I will get an "the email address has been used" error if the associated Email of the current provider is the same as previous. In this case I want to link the current Auth account with the previous account.

I understand that I need to call the linkWithCredential:completion: method to link the accounts. But I first need to sign In the previous account but how can I tell which account to sign in? For example, if I log in via Facebook and get the "same email being used" error, how do I know at this point whether should I sign in via Google or the email/password?

One interesting thing is If I use Facebook or email/password to sign in first and later sign in with Google, firebase will automatically handle the linking but the default behaviour is to overwrite the previous Auth provider with Google and keep the UID...

I have found an useful post How to manage users' different authentication in firebase

But it only deal with a simpler situation where authentication are only two.

Upvotes: 1

Views: 1650

Answers (1)

bojeil
bojeil

Reputation: 30868

When you get the credential already exists error, you already have the email at that point, you then call fetchProvidersForEmail with that email which will lookup the provider IDs associated with that email. You then sign in the user with one of those providers. After you finish sign-in with the existing account, you call linkWithCredential:completion: with the original credential that caused the error to occur. This causes the accounts to link. The next time the user tries to sign in, they will be able to sign in to the same user with either provider.

Check FirebaseUI-iOS which already takes care of the whole flow for you. You can also check there source code to see how they handle such situations: https://github.com/firebase/FirebaseUI-iOS

Upvotes: 2

Related Questions