Link Multiple accounts in Firebase

Viewed 1011

I have been stuck with this problem for a long time and i decided to post my problem here.

My problem is to merge the accounts (Facebook and Google) in Firebase. Independently sign-up with either one of them works fine.

At first when the user Sign-up with google and later with Facebook (that has the same email address with google) it throws and error. I managed to handle the error as you see on my code below but i don't know how to merge both accounts.

Here is what i have done so far:

facebookSignin: function() {
  var self = this
  firebase.auth().signInWithPopup(facebookProvider).then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
      self.registerProfile()
  }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      console.log("ERROR:" + error)
      console.log("email is : " + error.email)

      if (errorCode == 'auth/account-exists-with-different-credential') {
          firebase.auth().fetchProvidersForEmail(error.email).then(providers => {
                 //providers returns this array -> ["google.com"]
                 console.log("Providers:" + providers)
                 console.log("Credential: " + JSON.stringify(error.credential))

                 firebase.auth().currentUser.link(error.credential).then(function(user) {
                      console.log("Account linking success", user);
                  });
          }).catch(function(error){
              console.log("error:" + error)
          })
      }
      console.log("error code:" + error.code+ "error msg:" + error.message)
  });
  1. First i already Signed up with google
  2. Now i want to login with Facebook with the same email address I get the current-user null obviously because the user is not signed in, this is the error: error:TypeError: __WEBPACK_IMPORTED_MODULE_1_firebase___default.a.auth(...).currentUser is null .

I read the documentation about the merge part but still could not figure this out. https://firebase.google.com/docs/auth/web/account-linking#link-federated-auth-provider-credentials-to-a-user-account

I really appreciate the help.

1 Answers

After you fetchProvidersForEmail and figure out the existing Google user, you have to first login to that existing account:

firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider().setCustomParameters({login_hint: error.email})...

After that completes, you then:

firebase.auth().currentUser.linkWithCredential(error.credential)

So the user first has to verify ownership of the existing account before linking the Facebook account.

Related