Home > Back-end >  How to check for new user when log in with google authentication?
How to check for new user when log in with google authentication?

Time:12-16

I want to know if user is new or exists . I want to show additional View if user is new. I have implemented google sign in using this link https://developers.google.com/identity/sign-in/android/sign-in . Everything is working fine but addition i want to know if user is new or not. if log in user is new i want to do some Stuffs.

Here is my code for login using Google Authenticaion.

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Objects;

public class Login extends AppCompatActivity {

    private static final int RC_SIGN_IN = 100;
    LinearLayout button;
    GoogleSignInClient mGoogleSignInClient;
    GoogleSignInAccount account;
    DatabaseReference databaseReference;
    ProgressDialog progressDialog;
    long childTotal = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        button = findViewById(R.id.loginBtn);

        getWindow().setStatusBarColor(getResources().getColor(R.color.white));

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(Login.this, gso);
        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");

        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                childTotal = snapshot.getChildrenCount();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });



        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = new ProgressDialog(Login.this);
                progressDialog.setMessage("Please wait . . . ");
                progressDialog.setCancelable(false);
                progressDialog.show();
                signIn();

            }
        });

    }

    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
             account = completedTask.getResult(ApiException.class);
            // Signed in successfully, show authenticated UI.
            if (account!=null){
                addUserDataToDatabase();
                startActivity(new Intent(Login.this, MainActivity.class));
                progressDialog.dismiss();
                finish();
            }

        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            progressDialog.dismiss();
//            Toast.makeText(this, "Request cancelled by user.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account!=null) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    private void addUserDataToDatabase(){
        UserModel userModel = new UserModel();
        userModel.setName(account.getDisplayName());
        userModel.setEmail(account.getEmail());
        if (account.getPhotoUrl()==null){
            userModel.setPicture("No image available");
        }else {
            userModel.setPicture(String.valueOf(account.getPhotoUrl()));
        }
        databaseReference.child(Objects.requireNonNull(account.getDisplayName()))
                .setValue(userModel);
    }
}

CodePudding user response:

If you want to check if the user is new in Firebase, then you can use my answer from the following post:

If you don't want to use Firebase authentication, but I highly recommend you implement it, then you can add the user object in Firestore or in the Realtime Database.

Since you're using Java, for checking a user for existence in Firestore, please check the following answer:

And for checking a user for existence in the Realtime Database, then please check the following answer:

So when a user creates a new account, first check if the UID already exists in the database. If it doesn't, then the user is new, otherwise is an existing user.

  • Related