Search code examples
reactjsfirebasefirebase-authentication

Firebase Anonymous User escalation does not seem to work


I'm trying to escalate an anonymous user to their google credentials and use the same uid as the anonymous instance...

Any way I do it, it creates a new user... Why is this?

I would greatly appreciate help, I'm really stuck and the documentation isn't much help since it's incomplete.

https://firebase.google.com/docs/auth/web/anonymous-auth

import React, { useState } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInWithPopup, GoogleAuthProvider, linkWithCredential, signInAnonymously } from 'firebase/auth';

// Initialize Firebase with your config
const firebaseConfig = {
  // your config here
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

const AuthComponent = () => {
  const signInWithGoogle = async () => {
    try {
      const provider = new GoogleAuthProvider();
      const result = await signInWithPopup(auth, provider);

      // If the user is currently signed in anonymously, link their accounts
      if (auth.currentUser && auth.currentUser.isAnonymous) {
        const credential = GoogleAuthProvider.credentialFromResult(result);
        await linkWithCredential(auth.currentUser, credential);
        console.log('Anonymous account upgraded');
      } else {
        // Handle successful sign in
        console.log('Google sign-in success', result.user);
      }
    } catch (error) {
      console.error('Error with Google sign-in or account linking', error);
    }
  };

  return (
    <button onClick={signInWithGoogle}>Sign In with Google</button>
  );
};

export default AuthComponent;



Solution

  • You're not following the instructions exactly. The documentation says (emphasis mine):

    When the user signs up, complete the sign-in flow for the user's authentication provider up to, but not including, calling one of the Auth.signInWith methods.

    You're not supposed to use a signInWith method because that signs in the user and creates a new account for them if one wasn't already created.

    The documentation goes on to say:

    Pass the AuthCredential object to the sign-in user's link method

    Then shows how to use linkWithCredential to link the Google account credentials to the anonymous user account. If you want a popup, you can use linkWithPopup (instead of signInWithPopup).

    See: Firebase: How to convert an anonymous account to a permanent google account