@Bojeil's answer is the right one, however I wanted to add some color to it.
Why does Firebase Work This Way??
First, why the heck doesn't Firebase just deal with this and not involve me? IOW, why are we getting the auth/account-exists-with-different-credential
error in the first place?
Google believes (rightly or wrongly) that Facebook (and other) logins may be using non-verified email addresses (see this closed issue among others). The security issue with this flow for non-verified emails is as follows:
- Alice creates account in your app with alice@gmail.com.
- Eve adds alice@gmail.com as a non-verified email in their Facebook account.
- Eve logs in to your app using their own Facebook account, with the non-verified alice@gmail.com email address.
- Firebase attaches Eve's Facebook account to Alice's account in your application -- and Eve has now gained access to Alice's data.
Therefore, at step 4, Firebase refuses to do this, and instead returns the auth/account-exists-with-different-credential
failure to your application. Your application now requires Alice to login with her Google account (which Eve cannot do) in order to link the Facebook account to the same identity as the Google account.
What about Authenticating with Facebook First?
The reason this does not happen if the user logs in with Facebook first is that the since Google is the trusted authority for @gmail.com addresses, we know that Alice is simply logging in to her own account.
In this last situation, Firebase automatically links the Google account and removes the previous Facebook login from the account identity. This is to avoid another attack vector: if Eve can create an application account via her Facebook account and Alice's email address before Alice logs in, Eve has gained access to Alice's account in advance. In other words, Alice may happily create an account / log in as alice@gmail.com, not realizing that Eve's Facebook account was already attached to that login, and that Eve can therefore log in to the account. Since Firebase simply removes the non-canonical Facebook login, that attack vector is eliminated.
How
Again, @bojeil's answer is correct assuming you want to keep the Firebase "Link accounts that use the same email" setting. However, note that in browser environments obtaining the canonical credentials via popup will generally not work, because the second popup will not be a direct result of a user action, and the browser will block it.
One solution to this is to perform the canonical login via redirect. Another solution is to surface the credentials issue to the user, and have them click another button explicitly in order to login with the canonical credentials for the account. Since the second login is now a direct result of a user action, the popup will not be blocked.