I am try to link a Twitter Auth Provider to an email and password account via a flutter application using Firebase. I first want to sign in/up with email and password, then sometime down the road (a few hours, a few days, whenever...) authenticate with a user's Twitter account and associate it with that email and password account.
The code seems pretty straight forward but whenever I try to call signInWithProvider(TwitterAuthProvider())
followed by linkWithCredential(twitterAuthCredential.credential)
, the current user FirebaseAuth.instance.currentUser
is signed out and replaced with the twitter user and I get an error that indicates the provider is already linked to the current user:
Exception has occurred. FirebaseAuthException ([firebase_auth/provider-already-linked] User has already been linked to the given provider.)
Is the only way to link an account is if it's during signup/sign in when the credentials are retreived?
I've seen the solutions that init different apps but I'm hoping there's another way.
The option alluded to here - to change providers per email has been moved to Authentication > Settings but the default value is "Link accounts that use the same email"
I'm aware the instructions say "up to but not including the signInWith
calls" but I have limited options of getting the user's password well after they've already logged in, for security reasons, and I can't store their password, also for security best practices.
The twitter account I'm using, using the same email as the Twitter account.
Thanks,
final currentUser = FirebaseAuth.instance.currentUser; // already logged in with email and password
if (currentUser != null) {
TwitterAuthProvider twitterProvider = TwitterAuthProvider();
UserCredential twitterAuthCredential = await FirebaseAuth.instance.signInWithProvider(twitterProvider);
if (twitterAuthCredential.credential != null) {
await currentUser.linkWithCredential(twitterAuthCredential.credential!);
} else {
debugPrint('Could not link Twitter auth credentials');
}
}