Flutter, Dart and FirebaseAuth: How do I link a sign to a user?

Viewed 983

I'm experimenting with Flutter, Dart, and FirebaseAuth. I've been able to successfully login with a Google sign in, but when I try to login with a Facebook sign-in I get told "An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address."

This is because firebase auth is basing everything on the user's email and I've already signed in using Google. So it's not allowing a sign in with Facebook.

In some code I did years ago I just got the user and use .lineWithCredential(facebookAuthCred) to complete the link up with the established Google account in Firebase. But with the Dart implementation this doesn't work because FirebaseAuth.instance.currentUser() is returning a null. The docs on the error coming back from .signInWithCredential(facebookAuthCred) tell me to do .fetchSignInMethodForEmail(...) except that without a login I don't have an email address to pass to it.

So I'm in this situation. If a user re-starts the app and selects Facebook instead of Google, how can I link the accounts when I don't have a FirebaseUser nor an email address?

The only thing I've seen on the net so far is people saying you have to get the user to log in with their Google account first, but Logging in Google just to then login Facebook is a really terrible UI experience.

I'm struggling to figure this out.

1 Answers

You'll first need to sign the user in to Firebase Authentication with their existing Google account. Then you sign them in with Facebook, and create an AuthCredential through FacebookAuthProvider.getCredential(). Then you call linkWithCredential with the result from the previous call. This is the only way to link the two accounts.

If you want to allow users to sign in with whatever provider they prefer, but then creating separate accounts in your scenario where they have the same email address at multiple providers, you'll want to change the One account per email address setting in the Firebase Authentication console.

Related