skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. From your code it seems like you’re linking a provider to the existing anonymous account.

    In that scenario you should not delete the anonymous account (as it’ll just create a new account, as you see), but just link the provider. Once that process is complete, you’ll have a single account, with the same UID as your original anonymous user had, but it’ll no longer be an anonymous user.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search