27

A new bee to Firebase, I am trying out the Firebase Authentication and trying to check if user is logged-in.
code:

null != mAuth.getCurrentUser();

And this returns true though I am not logged in but I have enabled annonymous login and I thought that could be the issue but when I check mAuth.getCurrentUser().isAnonymous() I am getting false.

Inspecting mAuth.getCurrentUser() on the IDE shows this: enter image description here

Any directions here?

dsharew
  • 10,377
  • 6
  • 49
  • 75
  • 1
    are you sure you're completely signed out from the previous sign-in? You have to do `firebaseAuth.signOut()` **and** `Auth.GoogleSignInApi.signOut(apiClient)` – ataulm Jun 16 '17 at 09:39
  • Thanks that was my mistake; I was experimenting with the email password sign in the past few days so the authentication was cached. If you post it as an answer I will accept it or I remove the question it does not seem to be relevant enough – dsharew Jun 16 '17 at 11:19

7 Answers7

30

I think it works like the :

FirebaseAuth.getInstance().getCurrentUser()

It should return null if a user is not logged in.

Ashiq Muhammed
  • 376
  • 2
  • 9
  • it's strange but on android oreo it doesn't work for me – Vlad Nov 28 '17 at 09:40
  • 1
    "There are some cases where getCurrentUser will return a non-null FirebaseUser". Official docs: https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user – Andrew Jun 13 '18 at 10:56
20

I've had a similar issue and it was that signing out of Firebase is not enough - it will sign in automatically again.

It's necessary also to sign out using the GoogleSignInApi:

firebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(apiClient);
ataulm
  • 15,195
  • 7
  • 50
  • 92
7

To check if user is logged in:

 private FirebaseAuth firebaseAuth;
 FirebaseAuth.AuthStateListener mAuthListener;

Then in your onCreate:

     firebaseAuth = FirebaseAuth.getInstance();

      mAuthListener = new FirebaseAuth.AuthStateListener(){
                @Override
                public  void  onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if(user!=null){
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
}
                }


            };

This can be created in an auth state class or an interface.Then you can simply call the auth state or check in whichever activity you want to check it in with:

Checking the auth state when an activity is running:

 @Override
    protected void onStart() {
        super.onStart();
        firebaseAuth.addAuthStateListener(mAuthListener);
    }


    @Override
    protected void onResume() {
        super.onResume();
        firebaseAuth.addAuthStateListener(mAuthListener);
        }




    @Override
    protected void onStop() {
        super.onStop();
        firebaseAuth.removeAuthStateListener(mAuthListener);
    }

Now about your login:After setting your boolean values to check the user is logged in state:(Default boolean set to false)

firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            progressBar.setVisibility(View.GONE);
                            if (!task.isSuccessful()) {
//set a your boolean to false
current_user_db.setValue(false);

and if user is successfully logged in,set it to true followed by your intent:

else {


String userid = firebaseAuth.getCurrentUser().getUid();
                            DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference("Users").child(userid);
                            current_user_db.setValue(true);
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();

                        }

you will then have a your node set to False if user is logged in or false if user is not successfully logged in.

RileyManda
  • 2,536
  • 25
  • 30
1

Kotlin version

if you use Kotlin Just do this:

//properties
var firebaseAuth: FirebaseAuth? = null
var mAuthListener: FirebaseAuth.AuthStateListener? = null    
//in onCreate function
firebaseAuth = FirebaseAuth.getInstance()
    mAuthListener = FirebaseAuth.AuthStateListener() {
        fun onAuthStateChanged(@NonNull firebaseAuth:FirebaseAuth) {
            val user = FirebaseAuth.getInstance().getCurrentUser()
            if (user != null)
            {
                val intent = Intent(this@LoginActivity, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }
    }
Oscar
  • 157
  • 1
  • 9
1

Just add the Following in your code:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
             //User is Logged in
        }else{
             //No User is Logged in
        }
0

This is how to do it in Kotlin with animation before switching to the next screen:

    private var mAuth: FirebaseAuth? = null
    private var user: FirebaseUser? = null
    private var mAuthListner: FirebaseAuth.AuthStateListener? = null

    mAuth = FirebaseAuth.getInstance()
            mAuthListner = FirebaseAuth.AuthStateListener {
                    firebaseAuth: FirebaseAuth ->
                user = firebaseAuth.currentUser
                if(user != null){
                    //Go to dashboard
                    splash_logo.alpha = 0f
                    splash_logo.animate().setDuration(3000).alpha(1f).withEndAction {
                        val intent = Intent(this, HomeActivity::class.java)
                        startActivity(intent)
                        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        finish()
                    }
                }else{
                    splash_logo.alpha = 0f
                    splash_logo.animate().setDuration(3000).alpha(1f).withEndAction {
                        val intent = Intent(this, MainActivity::class.java)
                        startActivity(intent)
                        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        finish()
                    }
                }
            }
exploitr
  • 843
  • 1
  • 14
  • 27
0
if (FirebaseAuth.getInstance().getCurrentUser()==null){
// user loged in already
 }else{
                Toast.makeText(this, "Please Login First", Toast.LENGTH_LONG).show();
            }
Sam
  • 241
  • 3
  • 7
  • 3
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive-feedback/upvotes from users, when the code is explained. – Amit Verma Feb 10 '21 at 12:04
  • sure i will, Thank you – Sam Feb 10 '21 at 17:55