본문 바로가기

카테고리 없음

23.03.7) 최종 프로젝트 작업을 진행한 88일차

firebase: error (auth/account-exists-with-different-credential).

 

콘솔 ➡ 해당 프로젝트 ➡ 인증메뉴 ➡ 인증방법 ➡ 고급메뉴에서 이메일 주소당 여러계정을 변경해주면 된다!

다만 이렇게 되면 이메일이 null값으로 출력된다 

 

밑의 코드로 작성하면 된다는데....시간이 없으니 추후에 진행해보는걸로 한다.

const providers = {
  google: new firebase.auth.GoogleAuthProvider(),
  facebook: new firebase.auth.FacebookAuthProvider(),
  twitter: new firebase.auth.TwitterAuthProvider(),
};

const handleAuthError = async (error) => {
  if (error.email && error.credential && error.code === 'auth/account-exists-with-different-credential') {
    // We need to retain access to the credential stored in `error.credential`
    // The docs suggest we use session storage, so we'll do that.

    sessionStorage.setItem('credential', JSON.stringify(error.credential));

    const signInMethods = await firebase.auth().fetchSignInMethodsForEmail(error.email); // -> ['google.com']
    const providerKey = signInMethods[0].split('.')[0]; // -> 'google'
    const provider = providers[providerKey]; // -> providers.google

    firebase.auth().signInWithRedirect(provider);
  }
};

const handleRedirect = async () => {
  try {
    const result = await firebase.auth().getRedirectResult();
    const savedCredential = sessionStorage.getItem('credential');

    // we found a saved credential in session storage
    if (result.user && savedCredential) {
      handleLinkAccounts(result.user, savedCredential);
    }
    return result;
  }
  catch (error) {
    handleAuthError(error);
  }
};

const handleLinkAccounts = (authUser, savedCredential) => {
  // Firebase has this little hidden gem of a method call fromJSON
  // You can use this method to parse the credential saved in session storage
  const token = firebase.auth.AuthCredential.fromJSON(savedCredential);

  const credential = firebase.auth.FacebookAuthProvider.credential(token);
  authUser.linkWithCredential(credential);

  // don't forget to remove the credential
  sessionStorage.removeItem('credential');
};

firebase.auth().onAuthStateChanged((authUser) => {
  handleRedirect();
});