Home > Software design >  How to detect if a firebaseuser already exist on SignInWithCredentialAsync
How to detect if a firebaseuser already exist on SignInWithCredentialAsync

Time:08-10

For my unity android&ios app i am using Firebase Authentification with GoogleSignIn.
On button press (OnSignIn) the user gets a GoogleSignIn popup, on completion im signing the user with those credentials into firebase with SignInWithCredentialAsync.
As Result i recieve the FirebaseUser, but for my api on a backend server i need to know if the user got just created or was already existent on firebase.

Edit: Forgot to mention this exact issue happens if a user deinstall my application and reinstall it. At this point user is null and it reruns SignInWithCredentialAsync process. (i cant delete user on my database on deinstall)

public void OnSignIn()
{
    if (fireBaseReady == true)
    {
        if (user != null)
        {
            LoggedInAlready("login", user);
        }
        else
        {
            loginButton.SetActive(false);
            GoogleSignIn.Configuration = configuration;
            GoogleSignIn.Configuration.UseGameSignIn = false;
            GoogleSignIn.Configuration.RequestIdToken = true;
            GoogleSignIn.Configuration.RequestEmail = true;
            GoogleSignIn.DefaultInstance.SignIn().ContinueWithOnMainThread(OnAuthenticationFinished);
        }
    }
}

internal void OnAuthenticationFinished(System.Threading.Tasks.Task<GoogleSignInUser> task)
{
    if (task.IsCanceled)
    {
        warning.text = "SignIn got canceled";
        anWarning.Play("Base Layer.FontButtonFadeLong", 0, 0);
    }
    else if (task.IsFaulted)
    {
        warning.text = "SignIn was Faulted";
        anWarning.Play("Base Layer.FontButtonFadeLong", 0, 0);
    }
    else
    { 
        userToken = task.Result.IdToken;
        Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(userToken, null);
        auth.SignInWithCredentialAsync(credential).ContinueWithOnMainThread(authTask =>
        {
            if (authTask.IsCanceled)
            {
                warning.text = "Authentification is canceled";
                anWarning.Play("Base Layer.FontButtonFadeLong", 0, 0);
            }
            else if (authTask.IsFaulted)
            {
                warning.text = "Authentification is faulted";
                anWarning.Play("Base Layer.FontButtonFadeLong", 0, 0);
            }
            else
            {
                user = authTask.Result;
                LoggedInAlready("register", user);  // LOGIN OR REGISTER
            }
        });
    }
}

CodePudding user response:

Please specify app environment. Android, iOS or what?

CodePudding user response:

The easiest way to check if the user was newly created is to compare their CreationTimestamp and LastSignInTimestamp in the user's metadata. If they are the same (or very close to each other), the user was just created.

  • Related