Search code examples
javascriptfirebasefirebase-authentication

Firestore Authentication Delete Anonymous User and Signin With Another Provider


My App sign users anonymously automatically

  function onAuthStateChanged(user: FirebaseAuthTypes.User | null) {
    console.log(
      "Auth State Changed... ",
      user?.uid,
      user?.phoneNumber,
      user?.isAnonymous,
      "<<App.js"
    );
    userCurrentSet(user);
    if (!user) auth().signInAnonymously();
    if (initializing && user) setInitializing(false);
  }
  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
  }, []);

to manage anonymous accounts I want to delete the anonymous user before I sign in with the other account, something like this

const confirmCode = async () => {
    initilizingSet(true);
    confirm &&
      confirm.verificationId &&
      userCurrent &&
      (await userCurrent
        // -------> Trying to link the anonymous user with PhoneProvider
        .linkWithCredential(
          auth.PhoneAuthProvider.credential(confirm.verificationId, pinNumber)
        )
        .catch((e) => {
          console.log(e.code, "<<errCode");
          // -------> If the linking fails because the user already 
          //  has a different account, I delete the anonymous user 
          //  and login with new account
          if (e.code === "auth/credential-already-in-use") {
            userCurrent // currentuser Auth Object
              .delete() // Auth() delete current user method
              .then(() =>
                confirm.confirm(pinNumber).catch((e) => {
                  console.log(e);
                  initilizingSet(false);
                })
              )
              .catch((e) => {
                console.log(e);
                initilizingSet(false);
              });
          } else {
            initilizingSet(false);
          }
        }));
  };

my problem is with the subscriber kicking in and signing users anonymously again before my intentional signin, and I end up with a new anonymous user with a different id!

Any idea how to work around this?


Solution

  • The best way I could resolve my issue is by using the auth().deleteUser() method from the firebase/auth package, the delete command will delete a user from the Firebase Authentication List, and since changes on Authentication List isn't pushed in realtime to the App no event is triggered, hence I got the chance to process the new Login.