flutterfire icon indicating copy to clipboard operation
flutterfire copied to clipboard

🐛 [firebase_auth] linkWithCredential() throws email-already-in-use exception in flutter app

Open ablbol opened this issue 1 year ago • 30 comments

Bug report

Describe the bug I have a Flutter app that makes use of Firebase Auth. I am following the instructions over here to link different auth accounts, but I keep getting email-already-in-use exception every time I call linkWithCredential().

Steps to reproduce

Here are the steps that I am taking:

First, I sign in the user with a Google account by calling this function:

  Future<UserCredential> signInWithGoogle() async {
    final googleSignInAccount = await googleSignIn.signIn();

    if (googleSignInAccount != null) {
      final googleSignInAuthentication =
          await googleSignInAccount.authentication;

      final credential = GoogleAuthProvider.credential(
        accessToken: googleSignInAuthentication.accessToken,
        idToken: googleSignInAuthentication.idToken,
      );

      return auth.signInWithCredential(credential);
    } else {
      throw FirebaseAuthException(
        code: 'ERROR_GOOGLE_LOGIN_FAILED',
        message: 'Failed to login with google',
      );
    }
  }

// call the function to sign in the user using Google
final userCredential = await signInWithGoogle();

Now that the user is signed in using Google, I get a Credential object for email and password like this:

// The email used here is the same email I am using with Google
final credential = EmailAuthProvider.credential(email: email, password: password);

Now, pass the Credential object to the sign-in user's linkWithCredential() method like this:

  // userCredential was obtained when we signed in the user with Google
  await userCredential.user?.linkWithCredential(authCredential);

When the linkWithCredential() function gets called, I get the exception email-already-in-use exception!! Because of this exception, the two auth accounts are not linked.

How can I avoid this exception and link the two accounts?

Expected behavior

I expect that the Gmail and password accounts get linked.

Sample project

I am sorry, my project is too large to share.


Additional context

Add any other context about the problem here.


Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.16.3, on macOS 14.1.2 23B92 darwin-x64, locale en-AE)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
[✓] Xcode - develop for iOS and macOS (Xcode 15.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] VS Code (version 1.85.1)
[✓] Connected device (4 available)
[✓] Network resources

• No issues found!

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand
flutter pub deps -- --style=compact
Dart SDK 3.2.3
Flutter SDK 3.16.3
oolfa 1.4.7+54

dependencies:
- android_id 0.3.6 [flutter]
- audio_waveforms 1.0.4 [flutter]
- badges 3.1.2 [flutter]
- cached_network_image 3.3.1 [cached_network_image_platform_interface cached_network_image_web flutter flutter_cache_manager octo_image]
- carousel_slider 4.2.1 [flutter]
- cloud_firestore 4.14.0 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- cloud_functions 4.6.0 [cloud_functions_platform_interface cloud_functions_web firebase_core firebase_core_platform_interface flutter]
- connectivity_plus 5.0.2 [flutter flutter_web_plugins connectivity_plus_platform_interface js meta nm]
- cupertino_icons 1.0.6
- device_info_plus 9.1.1 [device_info_plus_platform_interface ffi file flutter flutter_web_plugins meta win32 win32_registry]
- dotted_border 2.1.0 [flutter path_drawing]
- firebase_analytics 10.8.0 [firebase_analytics_platform_interface firebase_analytics_web firebase_core firebase_core_platform_interface flutter]
- firebase_app_check 0.2.1+8 [firebase_app_check_platform_interface firebase_app_check_web firebase_core firebase_core_platform_interface flutter]
- firebase_auth 4.16.0 [firebase_auth_platform_interface firebase_auth_web firebase_core firebase_core_platform_interface flutter meta]
- firebase_core 2.24.2 [firebase_core_platform_interface firebase_core_web flutter meta]
- firebase_crashlytics 3.4.9 [firebase_core firebase_core_platform_interface firebase_crashlytics_platform_interface flutter stack_trace]
- firebase_database 10.4.0 [firebase_core firebase_core_platform_interface firebase_database_platform_interface firebase_database_web flutter]
- firebase_messaging 14.7.10 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta]
- firebase_remote_config 4.3.8 [firebase_core firebase_core_platform_interface firebase_remote_config_platform_interface firebase_remote_config_web flutter]
- firebase_storage 11.6.0 [firebase_core firebase_core_platform_interface firebase_storage_platform_interface firebase_storage_web flutter]
- firebase_ui_firestore 1.6.1 [cloud_firestore firebase_ui_localizations firebase_ui_shared flutter]
- flash 3.1.0 [flutter]
- flutter 0.0.0 [characters collection material_color_utilities meta vector_math web sky_engine]
- flutter_dotenv 5.1.0 [flutter]
- flutter_facebook_auth 6.0.3 [flutter flutter_facebook_auth_platform_interface flutter_facebook_auth_web facebook_auth_desktop]
- flutter_hooks 0.20.4 [flutter]
- flutter_image_compress 2.1.0 [flutter flutter_image_compress_platform_interface flutter_image_compress_common flutter_image_compress_web flutter_image_compress_macos]
- flutter_launcher_icons 0.13.1 [args checked_yaml cli_util image json_annotation path yaml]
- flutter_local_notifications 16.3.0 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone]
- flutter_localizations 0.0.0 [flutter intl characters clock collection material_color_utilities meta path vector_math web]
- flutter_slidable 3.0.1 [flutter]
- flutter_svg 2.0.9 [flutter vector_graphics vector_graphics_codec vector_graphics_compiler]
- geocoding 2.1.1 [flutter geocoding_platform_interface geocoding_android geocoding_ios]
- geolocator 10.1.0 [flutter geolocator_platform_interface geolocator_android geolocator_apple geolocator_web geolocator_windows]
- go_router 13.0.1 [collection flutter flutter_web_plugins logging meta]
- google_sign_in 6.2.1 [flutter google_sign_in_android google_sign_in_ios google_sign_in_platform_interface google_sign_in_web]
- hooks_riverpod 2.4.9 [collection flutter flutter_hooks flutter_riverpod riverpod state_notifier]
- http 1.1.2 [async http_parser meta web]
- image_cropper 5.0.1 [flutter image_cropper_platform_interface image_cropper_for_web]
- image_picker 1.0.7 [flutter image_picker_android image_picker_for_web image_picker_ios image_picker_linux image_picker_macos image_picker_platform_interface image_picker_windows]
- intl 0.18.1 [clock meta path]
- just_audio 0.9.36 [just_audio_platform_interface just_audio_web audio_session rxdart path path_provider async uuid crypto meta flutter]
- mask_text_input_formatter 2.7.0 [flutter]
- material_design_icons_flutter 7.0.7296 [flutter]
- open_mail_app 0.4.5 [platform url_launcher flutter]
- package_info_plus 5.0.1 [ffi flutter flutter_web_plugins http meta path package_info_plus_platform_interface web win32]
- path 1.8.3
- path_provider 2.1.2 [flutter path_provider_android path_provider_foundation path_provider_linux path_provider_platform_interface path_provider_windows]
- permission_handler 11.1.0 [flutter meta permission_handler_android permission_handler_apple permission_handler_html permission_handler_windows permission_handler_platform_interface]
- photo_view 0.14.0 [flutter]
- purchases_flutter 6.15.0 [flutter freezed_annotation json_annotation]
- rate_my_app 2.0.0 [shared_preferences flutter_rating_bar flutter]
- rxdart 0.27.7
- scrollable_positioned_list 0.3.8 [flutter collection]
- share_plus 7.2.1 [cross_file meta mime flutter flutter_web_plugins share_plus_platform_interface file url_launcher_web url_launcher_windows url_launcher_linux url_launcher_platform_interface ffi win32]
- shared_preferences 2.2.2 [flutter shared_preferences_android shared_preferences_foundation shared_preferences_linux shared_preferences_platform_interface shared_preferences_web shared_preferences_windows]
- shimmer 3.0.0 [flutter]
- showcaseview 2.0.3 [flutter]
- stack_trace 1.11.1 [path]
- store_redirect 2.0.1 [flutter]
- swipe_to 1.0.5 [flutter]
- timeago 3.6.0 [intl]
- url_launcher 6.2.3 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows]
- uuid 3.0.7 [crypto]
- webview_flutter 4.4.4 [flutter webview_flutter_android webview_flutter_platform_interface webview_flutter_wkwebview]

dev dependencies:
- flutter_test 0.0.0 [flutter test_api matcher path fake_async clock stack_trace vector_math async boolean_selector characters collection material_color_utilities meta source_span stream_channel string_scanner term_glyph web]
- flutter_web_plugins 0.0.0 [flutter characters collection material_color_utilities meta vector_math web]
- mocktail 1.0.1 [collection matcher test_api]
- very_good_analysis 5.1.0

transitive dependencies:
- _fe_analyzer_shared 61.0.0 [meta]
- _flutterfire_internals 1.3.16 [collection firebase_core firebase_core_platform_interface flutter meta]
- analyzer 5.13.0 [_fe_analyzer_shared collection convert crypto glob meta package_config path pub_semver source_span watcher yaml]
- archive 3.3.6 [crypto path pointycastle]
- args 2.3.2
- async 2.11.0 [collection meta]
- audio_session 0.1.14 [flutter flutter_web_plugins rxdart meta]
- boolean_selector 2.1.1 [source_span string_scanner]
- cached_network_image_platform_interface 4.0.0 [flutter flutter_cache_manager]
- cached_network_image_web 1.1.1 [cached_network_image_platform_interface flutter flutter_cache_manager]
- characters 1.3.0
- checked_yaml 2.0.2 [json_annotation source_span yaml]
- cli_util 0.4.0 [meta path]
- clock 1.1.1
- cloud_firestore_platform_interface 6.1.0 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- cloud_firestore_web 3.9.0 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js]
- cloud_functions_platform_interface 5.5.11 [firebase_core flutter meta plugin_platform_interface]
- cloud_functions_web 4.6.11 [cloud_functions_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js]
- collection 1.18.0
- connectivity_plus_platform_interface 1.2.4 [flutter meta plugin_platform_interface]
- convert 3.1.1 [typed_data]
- cross_file 0.3.3+4 [js meta]
- crypto 3.0.2 [typed_data]
- dbus 0.7.8 [args ffi meta xml]
- device_info_plus_platform_interface 7.0.0 [flutter meta plugin_platform_interface]
- facebook_auth_desktop 1.0.2 [flutter http flutter_secure_storage flutter_facebook_auth_platform_interface]
- fake_async 1.3.1 [clock collection]
- ffi 2.0.1
- file 6.1.4 [meta path]
- file_selector_linux 0.9.2+1 [cross_file file_selector_platform_interface flutter]
- file_selector_macos 0.9.3+3 [cross_file file_selector_platform_interface flutter]
- file_selector_platform_interface 2.6.1 [cross_file flutter http plugin_platform_interface]
- file_selector_windows 0.9.3+1 [cross_file file_selector_platform_interface flutter]
- firebase_analytics_platform_interface 3.9.0 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_analytics_web 0.5.5+12 [_flutterfire_internals firebase_analytics_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js]
- firebase_app_check_platform_interface 0.1.0+10 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_app_check_web 0.1.0+10 [_flutterfire_internals firebase_app_check_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins js]
- firebase_auth_platform_interface 7.0.9 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_auth_web 5.8.13 [firebase_auth_platform_interface firebase_core firebase_core_web flutter flutter_web_plugins http_parser js meta]
- firebase_core_platform_interface 5.0.0 [collection flutter flutter_test meta plugin_platform_interface]
- firebase_core_web 2.10.0 [firebase_core_platform_interface flutter flutter_web_plugins js meta]
- firebase_crashlytics_platform_interface 3.6.16 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_platform_interface 0.2.5+16 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_database_web 0.2.3+16 [firebase_core firebase_core_web firebase_database_platform_interface flutter flutter_web_plugins js]
- firebase_messaging_platform_interface 4.5.18 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_messaging_web 3.5.18 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta]
- firebase_remote_config_platform_interface 1.4.16 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface]
- firebase_remote_config_web 1.4.16 [firebase_core firebase_core_web firebase_remote_config_platform_interface flutter flutter_web_plugins js]
- firebase_storage_platform_interface 5.1.3 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface]
- firebase_storage_web 3.6.17 [_flutterfire_internals async firebase_core firebase_core_web firebase_storage_platform_interface flutter flutter_web_plugins http js meta]
- firebase_ui_localizations 1.10.1 [flutter flutter_localizations path]
- firebase_ui_shared 1.4.1 [flutter]
- flutter_cache_manager 3.3.1 [clock collection file flutter http path path_provider rxdart sqflite uuid]
- flutter_facebook_auth_platform_interface 5.0.0 [flutter plugin_platform_interface]
- flutter_facebook_auth_web 5.0.0 [flutter flutter_web_plugins js flutter_facebook_auth_platform_interface]
- flutter_image_compress_common 1.0.3 [flutter flutter_image_compress_platform_interface]
- flutter_image_compress_macos 1.0.1 [flutter flutter_image_compress_platform_interface]
- flutter_image_compress_platform_interface 1.0.3 [flutter plugin_platform_interface cross_file]
- flutter_image_compress_web 0.1.3+2 [flutter flutter_web_plugins flutter_image_compress_platform_interface js]
- flutter_local_notifications_linux 4.0.0+1 [dbus ffi flutter flutter_local_notifications_platform_interface path xdg_directories]
- flutter_local_notifications_platform_interface 7.0.0+1 [flutter plugin_platform_interface]
- flutter_plugin_android_lifecycle 2.0.7 [flutter]
- flutter_rating_bar 4.0.1 [flutter]
- flutter_riverpod 2.4.9 [collection flutter meta riverpod state_notifier]
- flutter_secure_storage 9.0.0 [flutter flutter_secure_storage_linux flutter_secure_storage_macos flutter_secure_storage_platform_interface flutter_secure_storage_web flutter_secure_storage_windows meta]
- flutter_secure_storage_linux 1.1.3 [flutter flutter_secure_storage_platform_interface]
- flutter_secure_storage_macos 3.0.0 [flutter flutter_secure_storage_platform_interface]
- flutter_secure_storage_platform_interface 1.0.1 [flutter plugin_platform_interface]
- flutter_secure_storage_web 1.1.1 [flutter flutter_secure_storage_platform_interface flutter_web_plugins js]
- flutter_secure_storage_windows 3.0.0 [ffi flutter flutter_secure_storage_platform_interface path path_provider win32]
- freezed_annotation 2.2.0 [collection json_annotation meta]
- geocoding_android 2.1.0 [flutter geocoding_platform_interface]
- geocoding_ios 2.1.0 [flutter geocoding_platform_interface]
- geocoding_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- geolocator_android 4.3.1 [flutter geolocator_platform_interface uuid]
- geolocator_apple 2.3.2 [flutter geolocator_platform_interface]
- geolocator_platform_interface 4.1.1 [flutter plugin_platform_interface vector_math meta]
- geolocator_web 2.2.0 [flutter flutter_web_plugins geolocator_platform_interface]
- geolocator_windows 0.2.1 [flutter geolocator_platform_interface]
- glob 2.1.2 [async collection file path string_scanner]
- google_identity_services_web 0.2.1 [js meta]
- google_sign_in_android 6.1.5 [flutter google_sign_in_platform_interface]
- google_sign_in_ios 5.7.0 [flutter google_sign_in_platform_interface pigeon]
- google_sign_in_platform_interface 2.4.0 [flutter plugin_platform_interface quiver]
- google_sign_in_web 0.12.0+5 [flutter flutter_web_plugins google_identity_services_web google_sign_in_platform_interface http js]
- http_parser 4.0.2 [collection source_span string_scanner typed_data]
- image 4.0.15 [archive meta xml]
- image_cropper_for_web 3.0.0 [flutter flutter_web_plugins image_cropper_platform_interface js]
- image_cropper_platform_interface 5.0.0 [flutter plugin_platform_interface http]
- image_picker_android 0.8.8+2 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface]
- image_picker_for_web 3.0.1 [flutter flutter_web_plugins image_picker_platform_interface mime]
- image_picker_ios 0.8.8+4 [flutter image_picker_platform_interface]
- image_picker_linux 0.2.1+1 [file_selector_linux file_selector_platform_interface flutter image_picker_platform_interface]
- image_picker_macos 0.2.1+1 [file_selector_macos file_selector_platform_interface flutter image_picker_platform_interface]
- image_picker_platform_interface 2.9.1 [cross_file flutter http plugin_platform_interface]
- image_picker_windows 0.2.1+1 [file_selector_platform_interface file_selector_windows flutter image_picker_platform_interface]
- js 0.6.7 [meta]
- json_annotation 4.8.0 [meta]
- just_audio_platform_interface 4.2.2 [flutter plugin_platform_interface]
- just_audio_web 0.4.9 [just_audio_platform_interface flutter flutter_web_plugins]
- logging 1.1.1
- matcher 0.12.16 [async meta stack_trace term_glyph test_api]
- material_color_utilities 0.5.0 [collection]
- meta 1.10.0
- mime 1.0.4
- nm 0.5.0 [dbus]
- octo_image 2.0.0 [flutter]
- package_config 2.1.0 [path]
- package_info_plus_platform_interface 2.0.1 [flutter meta plugin_platform_interface]
- path_drawing 1.0.1 [vector_math meta path_parsing flutter]
- path_parsing 1.0.1 [vector_math meta]
- path_provider_android 2.2.0 [flutter path_provider_platform_interface]
- path_provider_foundation 2.3.1 [flutter path_provider_platform_interface]
- path_provider_linux 2.2.1 [ffi flutter path path_provider_platform_interface xdg_directories]
- path_provider_platform_interface 2.1.1 [flutter platform plugin_platform_interface]
- path_provider_windows 2.2.1 [ffi flutter path path_provider_platform_interface win32]
- permission_handler_android 12.0.1 [flutter permission_handler_platform_interface]
- permission_handler_apple 9.2.0 [flutter permission_handler_platform_interface]
- permission_handler_html 0.1.0+1 [flutter flutter_web_plugins permission_handler_platform_interface]
- permission_handler_platform_interface 4.0.2 [flutter meta plugin_platform_interface]
- permission_handler_windows 0.2.0 [flutter permission_handler_platform_interface]
- petitparser 5.4.0 [meta]
- pigeon 11.0.1 [analyzer args collection meta path yaml]
- platform 3.1.0
- plugin_platform_interface 2.1.6 [meta]
- pointycastle 3.6.2 [collection convert js]
- process 4.2.4 [file path platform]
- pub_semver 2.1.4 [collection meta]
- quiver 3.2.1 [matcher]
- riverpod 2.4.9 [meta stack_trace state_notifier]
- share_plus_platform_interface 3.3.1 [cross_file flutter meta mime plugin_platform_interface path_provider uuid]
- shared_preferences_android 2.1.4 [flutter shared_preferences_platform_interface]
- shared_preferences_foundation 2.2.2 [flutter shared_preferences_platform_interface]
- shared_preferences_linux 2.2.0 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface]
- shared_preferences_platform_interface 2.3.1 [flutter plugin_platform_interface]
- shared_preferences_web 2.1.0 [flutter flutter_web_plugins shared_preferences_platform_interface]
- shared_preferences_windows 2.2.0 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface]
- sky_engine 0.0.99
- source_span 1.10.0 [collection path term_glyph]
- sqflite 2.2.4+1 [flutter sqflite_common path]
- sqflite_common 2.4.2+2 [synchronized path meta]
- state_notifier 0.7.2+1 [meta]
- stream_channel 2.1.2 [async]
- string_scanner 1.2.0 [source_span]
- synchronized 3.0.1
- term_glyph 1.2.1
- test_api 0.6.1 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph]
- timezone 0.9.1 [path]
- typed_data 1.3.1 [collection]
- url_launcher_android 6.2.0 [flutter url_launcher_platform_interface]
- url_launcher_ios 6.2.1 [flutter url_launcher_platform_interface]
- url_launcher_linux 3.1.0 [flutter url_launcher_platform_interface]
- url_launcher_macos 3.1.0 [flutter url_launcher_platform_interface]
- url_launcher_platform_interface 2.2.0 [flutter plugin_platform_interface]
- url_launcher_web 2.2.1 [flutter flutter_web_plugins url_launcher_platform_interface web]
- url_launcher_windows 3.1.0 [flutter url_launcher_platform_interface]
- vector_graphics 1.1.9+1 [flutter vector_graphics_codec]
- vector_graphics_codec 1.1.9+1
- vector_graphics_compiler 1.1.9+1 [args meta path_parsing xml vector_graphics_codec path]
- vector_math 2.1.4
- watcher 1.1.0 [async path]
- web 0.3.0
- webview_flutter_android 3.12.0 [flutter webview_flutter_platform_interface]
- webview_flutter_platform_interface 2.6.0 [flutter meta plugin_platform_interface]
- webview_flutter_wkwebview 3.9.1 [flutter path webview_flutter_platform_interface]
- win32 5.0.3 [ffi]
- win32_registry 1.1.1 [ffi win32]
- xdg_directories 0.2.0+3 [meta path process]
- xml 6.3.0 [collection meta petitparser]
- yaml 3.1.1 [collection source_span string_scanner]

ablbol avatar Jan 14 '24 16:01 ablbol

@ablbol What platform are you seeing the error ? Can you provide the complete error log ? Please try to use the plugin example and check if using it, you get the same error or not.

darshankawar avatar Jan 15 '24 11:01 darshankawar

I was testing on a real Android 13 device. I tried both the Firebase Emulator and Firebase backend. I will try the plugin example and see if I get the same result.

ablbol avatar Jan 15 '24 11:01 ablbol

Can you tell me how to download the plugin example? I don't see any instructions.

ablbol avatar Jan 15 '24 12:01 ablbol

Ok, so I used the plugin example you mentioned and got the same exception: "The email address is already in use by another account." Here is the function that I used. I took the _signInWithGoogle() already in the example and added the code for linking the email/password account to the Gmail account. I added a comment in the code to explain.

  Future<void> _signInWithGoogle() async {
    // Trigger the authentication flow
    final googleUser = await GoogleSignIn().signIn();

    // Obtain the auth details from the request
    final googleAuth = await googleUser?.authentication;

    if (googleAuth != null) {
      // Create a new credential
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // Once signed in, return the UserCredential
      final userCredential = await auth.signInWithCredential(credential);

      // Create email/password credential object.  The email used here is the same email used in the Gmail sign in above
      final emailCredential = EmailAuthProvider.credential(
        email: '[email protected]',
        password: 'mypassword',
      );

      // Now link email/password account to the Gmail account. However, I get the Firebase Auth Exception 
      //  with code "email-already-in-use".  Linking is not working.  What should I do?
      await userCredential.user?.linkWithCredential(emailCredential);
    }
  }

ablbol avatar Jan 15 '24 17:01 ablbol

@ablbol Can you check if you are hitting https://github.com/firebase/flutterfire/issues/11661 ?

darshankawar avatar Jan 16 '24 10:01 darshankawar

Ok, so I looked at _anonymousAuth() function from the test that you sent me and I modified it. I first sign in anonymously then link current user to Email/password credential as shown in the comments. I did not get any exception when running this function and linking the Email/Password credential to the Anonymous user

  Future<void> _anonymousAuth() async {
    setIsLoading();

    try {
      // this was there from before
      await auth.signInAnonymously();

      // I added this line, using my own gmail
      final credential = EmailAuthProvider.credential(
        email: '[email protected]', 
        password: 'password',
      );

      // I added this line: linking email/password credential to current user 
      // No exception was thrown here
      FirebaseAuth.instance.currentUser?.linkWithCredential(credential);
    } on FirebaseAuthException catch (e) {
      setState(() {
        error = '${e.message}';
      });

      print('===> e: $e');
    } catch (e) {
      setState(() {
        error = '$e';
      });
    } finally {
      setIsLoading();
    }
  }

ablbol avatar Jan 16 '24 13:01 ablbol

Ok, does this mean the issue is resolved ?

darshankawar avatar Jan 17 '24 09:01 darshankawar

You asked me to test issue #11661 , so I did, and I told you that I did not run into any exceptions with that issue. But my issue is not resolved. I am stuck with the exception and can't release my app until there is a resolution.

ablbol avatar Jan 17 '24 09:01 ablbol

Thanks for the update. Using the code sample mentioned here and then using the same email id to login to google and emailAuth, is giving email-already-in-use exception, but since the same account is being used in both Authproviders, I am not sure if the exception is intended or not.

Based on the report, I'll keep the issue open for team's input / attention.

/cc @Lyokone

darshankawar avatar Jan 17 '24 11:01 darshankawar

@darshankawar, two auth accounts should be linkable ONLY if they share the same email. But receiving email-already-in-use exception when trying to link password and gmail accounts sharing the same email defeats the purpose of linking auth accounts in the first place.

ablbol avatar Jan 17 '24 11:01 ablbol

Hey @ablbol - are you certain the credential isn't already linked to another account? See documentation: https://firebase.google.com/docs/auth/android/account-linking

Quote:

The call to linkWithCredential will fail if the credentials are already linked to another user account. In this situation, you must handle merging the accounts and associated data as appropriate for your app:

To test completely remove the accounts you're seeing this error with from Firebase console auth users. Try again and see if it is the same problem.

russellwheatley avatar Jan 17 '24 12:01 russellwheatley

Hi @russellwheatley, I deleted all the users in my Firebase auth console and ran the same test where I first signed in with gmail account ([email protected]) then I linked Email/Password Credential (with same gmail email) to the currently logged in gmail user and ran into the same exception "The email address is already in use by another account".

However, I tried a strange test. I deleted all Firebase auth users again. Then I signed in using gmail account ([email protected]), then I linked Email/password Credential with different email ([email protected]) to the currently logged in gmail user ([email protected]) and to my surprised linking did work BUT HOW??? Isn't that dangerous??

ablbol avatar Jan 17 '24 14:01 ablbol

Hi @russellwheatley, I deleted all the users in my Firebase auth console and ran the same test where I first signed in with gmail account ([email protected]) then I linked Email/Password Credential (with same gmail email) to the currently logged in gmail user and ran into the same exception "The email address is already in use by another account".

However, I tried a strange test. I deleted all Firebase auth users again. Then I signed in using gmail account ([email protected]), then I linked Email/password Credential with different email ([email protected]) to the currently logged in gmail user ([email protected]) and to my surprised linking did work BUT HOW??? Isn't that dangerous??

It is perfectly fine, under the hood, it associates the provider with a Firebase user (and associated UID). The user has a primary email and it also keeps a list of providers with their associated email addresses. If there are any conflicts (i.e user uid associated with an email you're trying to link to another account), it throws the exception you're receiving.

In any event, I've just tested linking accounts and it works. Try this:

final prevUser = FirebaseAuth.instance.currentUser;

TwitterAuthProvider twitterProvider =
  TwitterAuthProvider();

final userCred =
  await auth.signInWithProvider(twitterProvider);

await prevUser?.linkWithCredential(
  userCred.credential!,
);

russellwheatley avatar Jan 17 '24 17:01 russellwheatley

Hi @russellwheatley, I have tried your test many times, and it is failing. In my case, prevUser is a user that signed in with gmail and the Credential is obtained with "EmailAuthProvider.credential()". However the test that is failing is when both the gmail and password accounts are using the same email. So the problem we have right now is how can I link my password account and gmail account when both accounts have the same email. I keep getting "The email address is already in use by another account".

ablbol avatar Jan 18 '24 03:01 ablbol

Hi @russellwheatley , have you made any decision on this issue? Right now, we can link two auth accounts that hold different emails, but we cannot link two auth accounts that hold the same email. I really appreciate your help in this.

ablbol avatar Jan 21 '24 13:01 ablbol

Ok, so I used the plugin example you mentioned and got the same exception: "The email address is already in use by another account." Here is the function that I used. I took the _signInWithGoogle() already in the example and added the code for linking the email/password account to the Gmail account. I added a comment in the code to explain.

  Future<void> _signInWithGoogle() async {
    // Trigger the authentication flow
    final googleUser = await GoogleSignIn().signIn();

    // Obtain the auth details from the request
    final googleAuth = await googleUser?.authentication;

    if (googleAuth != null) {
      // Create a new credential
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // Once signed in, return the UserCredential
      final userCredential = await auth.signInWithCredential(credential);

      // Create email/password credential object.  The email used here is the same email used in the Gmail sign in above
      final emailCredential = EmailAuthProvider.credential(
        email: '[email protected]',
        password: 'mypassword',
      );

      // Now link email/password account to the Gmail account. However, I get the Firebase Auth Exception 
      //  with code "email-already-in-use".  Linking is not working.  What should I do?
      await userCredential.user?.linkWithCredential(emailCredential);
    }
  }

@ablbol - going back to this. When you use this:

       final emailCredential = EmailAuthProvider.credential(
         email: '[email protected]',
         password: 'mypassword',
       );

Is this account already created in your Auth backend? i.e. you should see something like this in your Firebase Auth console: Screenshot 2024-01-22 at 10 21 48

Also - what setting is this in your Firebase console? Screenshot 2024-01-22 at 10 23 00

russellwheatley avatar Jan 22 '24 10:01 russellwheatley

Ok, so I used the plugin example you mentioned and got the same exception: "The email address is already in use by another account." Here is the function that I used. I took the _signInWithGoogle() already in the example and added the code for linking the email/password account to the Gmail account. I added a comment in the code to explain.

  Future<void> _signInWithGoogle() async {
    // Trigger the authentication flow
    final googleUser = await GoogleSignIn().signIn();

    // Obtain the auth details from the request
    final googleAuth = await googleUser?.authentication;

    if (googleAuth != null) {
      // Create a new credential
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // Once signed in, return the UserCredential
      final userCredential = await auth.signInWithCredential(credential);

      // Create email/password credential object.  The email used here is the same email used in the Gmail sign in above
      final emailCredential = EmailAuthProvider.credential(
        email: '[email protected]',
        password: 'mypassword',
      );

      // Now link email/password account to the Gmail account. However, I get the Firebase Auth Exception 
      //  with code "email-already-in-use".  Linking is not working.  What should I do?
      await userCredential.user?.linkWithCredential(emailCredential);
    }
  }

When using this code, in my Firebase auth console, I already have a Gmail account with the email "[email protected]," which is the same email as in the password credential below. In addition, in my Firebase auth console, under the settings tab, I have "Link accounts that use the same email" selected.

@ablbol - going back to this. When you use this:

       final emailCredential = EmailAuthProvider.credential(
         email: '[email protected]',
         password: 'mypassword',
       );

Is this account already created in your Auth backend? i.e. you should see something like this in your Firebase Auth console: Screenshot 2024-01-22 at 10 21 48

Also - what setting is this in your Firebase console? Screenshot 2024-01-22 at 10 23 00

ablbol avatar Jan 22 '24 10:01 ablbol

@ablbol - have you previously created an email/password user already using these details?

       final emailCredential = EmailAuthProvider.credential(
         email: '[email protected]',
         password: 'mypassword',
       );

which would appear in the Firebase auth console with the email provider icon as shown below: Screenshot 2024-01-22 at 10 21 48

russellwheatley avatar Jan 22 '24 11:01 russellwheatley

No, I have not. I only have a Gmail account with the same email as the one with the email/password credential I am trying to link to Gmail.

One thing I tried is to change the selection under the "User account linking" to "Create multiple accounts for each identity provider" but then calls to fetchSignInMethodsForEmail(email) gave me an empty list even though I already have Gmail account in my Firebase Auth Console. This seems to be similar to issue #11508, which is closed but does not seem to have been resolved!!.

@ablbol - have you previously created an email/password user already using these details?

       final emailCredential = EmailAuthProvider.credential(
         email: '[email protected]',
         password: 'mypassword',
       );

which would appear in the Firebase auth console with the email provider icon as shown below: Screenshot 2024-01-22 at 10 21 48

ablbol avatar Jan 22 '24 11:01 ablbol

Hmmm, there does appear to be some discrepancy from my testing. I think what you're trying to do should work. I'm going to look into this further tomorrow 👍

russellwheatley avatar Jan 22 '24 15:01 russellwheatley

Hello, I'm also facing the "email-already-in-use" error when linking the email/password provider after Google sign-up. As my requirement is for every user to have a password, I redirect the user to a password form after signing up with Google. Am sure that the code used to work when I last tested it about a month ago, Since then, I've been involved in other projects. Today, when I returned to the application, I discovered that the 'linkWithCredential' function is throwing an 'email-already-in-use' error.

This is my code :

   Future<AuthenticationUser> addPasswordProvider(String password) async {
    try {
      final user = firebaseAuth.currentUser;
      final credentials = authProviderService.getEmailCredential(
        email: user?.email as String,
        password: password,
      );
      final userCredentials = await user?.linkWithCredential(credentials);
      if (userCredentials != null) {
        final updatedUser = userCredentials.user!;
        final idTokenResult = await updatedUser.getIdTokenResult(true);
        return AuthenticationUser.fromFirebaseUser(
          updatedUser,
          claims: idTokenResult.claims ?? {},
        );
      }
      throw const AuthErrorUnknown();
    } on FirebaseAuthException catch (firebaseAuthException) {
      throw AuthenticationError.fromFirebase(firebaseAuthException);
    } catch (error) {
      throw const AuthErrorUnknown();
    }
  }

razzeguimohamedzied avatar Jan 22 '24 16:01 razzeguimohamedzied

I have tried to run several linking tests on 3 different auth providers to find out where there are possible problems. All tests were done under the following conditions:

  • Email enumeration is disabled.
  • Under "User account linking", I have "Link accounts that use the same email" selected.
  • Tests were only done on Password, Google, and Facebook providers.
  • All tests were done on auth providers that share the same email.

Here are the linking tests that failed. Please notice the pattern:

  1. Linking a non-existing Password Provider to an existing Google account has failed (email-already-in-use).
  2. Linking a non-existing Password Provider to an existing Facebook account has failed (email-already-in-use)
  3. Linking a non-existing Password Provider to existing Facebook and Google accounts has failed (email-already-in-use).

All other tests have passed. In particular, a couple of interesting tests that passed are:

  1. Linking a non-existing Google provider to an existing Password account has passed.
  2. Linking a non-existing Facebook provider to an existing Password account has passed.

Other linking tests that passed:

  1. Linking a non-existing Facebook provider to an existing Google account has passed.
  2. Linking a non-existing Google provider to an existing Facebook account has passed.

I hope that all this can help in resolving this issue. Thanks

ablbol avatar Jan 23 '24 07:01 ablbol

@ablbol - thanks for the report. I have found that an update to the Firebase SDKs have brought a breaking change 😅 .

If you want to revert the change in your Flutter android app, please add the following to your android/build.gradle:

// Add this block to use android BOM: 32.5.0
project.ext {
  set('FlutterFire', [
    FirebaseSDKVersion: "32.5.0",
  ])
}
// Above this line
allprojects {

I'm going to open an issue on the firebase-android-sdk and link it here for updates 🙏

russellwheatley avatar Jan 23 '24 15:01 russellwheatley

Hi @russellwheatley , your suggested update to the build.gradle did solve the problem of linking accounts in Android. I did not perform account linking on IOS. Does account linking work there by default, or do I need to make any changes from my side? Thanks for your help.

ablbol avatar Jan 23 '24 16:01 ablbol

Hi @russellwheatley, I tested Auth account linking on IOS, and the issue is unresolved. I am still getting email-already-in-use exception. Could you kindly let us know what needs to be done to resolve it? Thanks

ablbol avatar Jan 24 '24 04:01 ablbol

@ablbol - The last working firebase-ios-sdk version is 10.17.0. Please put this in your Podfile (ios/Podfile) to fix the bug:

# platform :ios, '11.0'
# Just below the above line is fine
$FirebaseSDKVersion = '10.17.0'

russellwheatley avatar Jan 24 '24 08:01 russellwheatley

@russellwheatley firebase-ios-sdk version is 10.17.0 does work. I have a question, though. When I tried the latest firebase-ios-sdk which is version 10.20.0, the issue was still there. Does that mean that there is no plan to fix this issue going forward? Please let us know so we can plan accordingly. Thanks

ablbol avatar Jan 24 '24 09:01 ablbol

@ablbol - I'm going to raise an issue on firebase-ios-sdk 👍

russellwheatley avatar Jan 24 '24 09:01 russellwheatley

@russellwheatley Please don't forget to raise an issue on Firebase-android-sdk as well so that we can resolve this once and for all. Thanks

ablbol avatar Jan 24 '24 09:01 ablbol

both ios and android issues are linked in this issue.

russellwheatley avatar Jan 24 '24 10:01 russellwheatley