10

I need to check if the user is signing in for the first time, and initialize their account with extra properties (points, membership, etc) if true.

May user change his device and wants login again on another device.

I'm using google sign-in method. I tried something like this.

if(FirebaseAuth.getInstance().getCurrentUser() != null){
                           Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
                       }

I sign-in with new account, so first time in this app, but it's show "Welcome again xyz" message anyway.

How can I detect if user exist on database before?

Full code

package com.mertg.testsignin;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
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.ConnectionResult;

import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.FirebaseDatabase;


public class Anamain extends AppCompatActivity {


    private String TAG = "Anamain";
    private SignInButton signIn;
    GoogleSignInClient mGoogleSignInClient;
    private int RC_SIGN_IN = 1;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anamain);

        signIn = (SignInButton)findViewById(R.id.googleBtn);

        mAuth = FirebaseAuth.getInstance();

        // Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                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 GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);

            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);


                // ...
            }
        }
    }



    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d("TAG", "signInWithCredential:success" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                       /* if (!task.isSuccessful()){
                        Log.d("TAG", "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        }*/
                       if(FirebaseAuth.getInstance().getCurrentUser() != null){
                           Toast.makeText(Anamain.this, "Welcome again xyz", Toast.LENGTH_SHORT).show();
                       }

                       else {
                            //Log.w("TAG", "signInWithCredential:failure", task.getException());
                           // Toast.makeText(Anamain.this, "Basaramadim", Toast.LENGTH_SHORT).show();
                            //updateUI(null);
                           Toast.makeText(Anamain.this, "Register Successful", Toast.LENGTH_SHORT).show();
                           FirebaseUser user = mAuth.getCurrentUser();
                           //updateUI(user);
                        }

                    }


                });

    }

    private void updateUI(FirebaseUser user) {
        GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        if(acct != null)    {
            String personName = acct.getDisplayName();

            Toast.makeText(this, "Sen Girdin" + personName, Toast.LENGTH_SHORT).show();
        }
    }

}

UPDATE

I get error: ';' expected for this line

mAuth.signInWithCredential(credential)

This is how ı replaced.

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d("TAG", "signInWithCredential:success" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
                if (isNewUser) {
                    Log.d(TAG, "Is New User!");
                } else {
                    Log.d(TAG, "Is Old User!");
                }
            }

        });

    }
Op.Kemal
  • 127
  • 1
  • 11

4 Answers4

8

How can I detect if user first time in Firebase?

If you want to check if the user logs in for the first time, it's the same thing if you check if a user is new. So to solve this, you can simply call AdditionalUserInfo's isNewUser() method:

Returns whether the user is new or existing

In the OnCompleteListener.onComplete callback like this:

OnCompleteListener<AuthResult> completeListener = new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
            if (isNewUser) {
                Log.d("TAG", "Is New User!");
            } else {
                Log.d("TAG", "Is Old User!");
            }
        }
    }
};

For more informations, please see the official documentation.

Edit: In order to make it work, you need to add a complete listener. Please see the code below:

mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
        if (isNewUser) {
            Log.d(TAG, "Is New User!");
        } else {
            Log.d(TAG, "Is Old User!");
        }
    }
});

Or even simpler:

mAuth.signInWithCredential(credential).addOnCompleteListener(this, completeListener);

In which, the completeListener object is the object that was defined first.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • For use this method,do i need to change or remove to "onActivityResult" or "firebaseAuthWithGoogle" events ? And where should i call "completeListener" method ? In the onActivityResult event ? – Op.Kemal Sep 11 '18 at 13:00
  • Ok i understand now,i need to replace after the "credential".But i can't figure ot how firebaseAuthWithGoogle event should be.Can you share inside of full code ? Thank you. – Op.Kemal Sep 11 '18 at 13:20
  • No, you should not remove anything. You should use this code in the exact place where you need to check if the user is new or not, right? – Alex Mamo Sep 11 '18 at 13:50
  • Yes.Your solution may right but i didn't yet.Can you check update. – Op.Kemal Sep 11 '18 at 14:35
  • No, no in that way. I'll update my answer now. – Alex Mamo Sep 11 '18 at 14:56
  • Please see now my updated answer. Is it ok now? – Alex Mamo Sep 11 '18 at 15:01
  • authCredential turns red.Cannot reselve symbol authCredential.I edit my update.Did i miss something ? – Op.Kemal Sep 11 '18 at 15:10
  • Just changed `authCredential` to `credential`. My mistake, sorry about that. Also updated my answer. Does it work now? – Alex Mamo Sep 11 '18 at 15:14
0

You can have user node in your database on which you can add key as uuid and value as its unique uuid, If your user comes for first time you will not get the uuid on the user node and hence you can add uuid there with initialization of your user in the database

Rishabh Saxena
  • 1,765
  • 15
  • 26
0

Make a isFirstTime = false type of flag in database. When the app is installed first time set it to true.

Sujin Shrestha
  • 1,203
  • 2
  • 13
  • 23
0

Just to share my previous implementation on the new user issue.

I have used Firebase Cloud Firestore in my project, so I have created another table to store my users' basic info.

First, I create a method namely createUser() but basically, it checks whether it is a first time user by querying the Firebase Cloud Firestore database. If not exists, create a document for the user, and you can perform your action towards them, look for //you can add some action here in the code below.

Below is the actual code for my previous project which includes a Role-Based Administration to control user access (Just for your reference if you are interested).

 public void createUser(){
        docRef = mFirestore.collection("users").document(auth.getCurrentUser().getUid());
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();

                   //if the user is already in the database, check the user role
                    if (document != null && document.exists()) {
                        User user = document.toObject(User.class);
                        if(user.getRoles().get("admin")==true){
                            Log.d(TAG, "Admin: true");
                            btn_admin.setVisibility(View.VISIBLE);
                        }

                        else{
                            Log.d(TAG, "Admin: false");
                            btn_admin.setVisibility(View.GONE);
                        }

                        Log.d(TAG, "DocumentSnapshot data: " + document.getData());
                    } else {
                         //check whether it's a new user
                         //if yes, create a new document containing the user details thru my User model

                        Log.d(TAG, "No such document");
                        btn_admin.setVisibility(View.GONE);
                        Map<String, Boolean> roles = new HashMap<>();
                        roles.put("editor", false);
                        roles.put("viewer", false);
                        roles.put("admin", false);
                        User user = new User(auth.getCurrentUser().getDisplayName(), auth.getCurrentUser().getUid(),auth.getCurrentUser().getEmail(), roles);
                        //you can add some action here

                        mFirestore.collection("users").document(auth.getCurrentUser().getUid())
                                .set(user, SetOptions.merge())
                                .addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Log.d(TAG, "DocumentSnapshot successfully written!");
                                    }
                                })
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Log.w(TAG, "Error writing document", e);
                                    }
                                });
                        //Log.d(TAG, "Created credential");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    }
Angus
  • 3,680
  • 1
  • 12
  • 27