2

Hello and thanks for your time.

I've been working on an android app using Firebase.

I've set up Firebase Authentication and the user can register with email and password and log in after email verification.

When the app opens, I check if the user is still logged in with the onStart() method, but I tried that after deleting the user from firebase and I could still log in!

Should I be checking this in another way?

@Override
public void onStart() {
    super.onStart();

    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}

******************************************* UPDATE *********************************************

Fixed the problem using AuthStateListener , but then I split the signIn and createAccount methods into 2 separate activities With that I also separated the createAccount() from signInWithEmailAndPassword() methods which made me add this mAuth = FirebaseAuth.getInstance() in both activities onCreate() method. In the logIn activity I added

mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser currentUser = mAuth.getCurrentUser(); ... } };

but now doesn't work. Am I forgetting something or just can't do this?

Here's the code I found relevant:

LogInActivity class onCreate():

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

    // Views
    emailEditText = findViewById(R.id.emailEditText);
    passwordEditText = findViewById(R.id.pswdEditText);

    // Buttons
    findViewById(R.id.logInButton).setOnClickListener(this);
    findViewById(R.id.forgottenPaswdTextButton).setOnClickListener(this);
    findViewById(R.id.registerTextButton).setOnClickListener(this);

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    // Check for user connection
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            // Check if user is signed in (non-null) and update UI accordingly.
            FirebaseUser currentUser = mAuth.getCurrentUser();
            if (currentUser != null) {
                Log.d(TAG, "onAuthStateChanged:signed_in:" + currentUser.getUid());
            } else {
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            updateUI(currentUser);
        }
    };
}

SignInActivity class onCreate():

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

    // Views
    emailEditText = findViewById(R.id.emailEditText);
    passwordEditText = findViewById(R.id.pswdEditText);
    passwordRetypedEditText = findViewById(R.id.pswdRetypeEditText);
    nameEditText = findViewById(R.id.nameEditText);

    // Buttons
    findViewById(R.id.signUpButton).setOnClickListener(this);
    findViewById(R.id.logInTextButton).setOnClickListener(this);

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

}
  • Have you sccessfully signed out before? – Alex Mamo Sep 21 '19 at 12:37
  • Havn't tried, but if I clear app cache and stuff it will disconect the user. Just won't detect he doesn't exists anymore. – Pedro Marques Sep 21 '19 at 12:58
  • @PedroMarques you forgot to add listener like `addAuthStateListener(AuthStateListener)` and then remove it in `onDestroy()` like `removeAuthStateListener(AuthStateListener)` to register or unregister listeners. – Jeel Vankhede Sep 24 '19 at 12:07
  • Well...i just completely missed that. Probably when I changed things up! I'll see how it goes but thank you very much for all the help!!! @JeelVankhede – Pedro Marques Sep 24 '19 at 12:19
  • Happy to help :) – Jeel Vankhede Sep 24 '19 at 12:21
  • oh and by the way! Do I have to add it either in the logIn activity and the signIn? In my app the launcher activity is the login one and then, if the user doesn't have an account it changes it to the sign in activity. Btw is there any way to rate users in here? @JeelVankhede – Pedro Marques Sep 24 '19 at 12:25
  • You can add listener in Login Activity as it's your launcher activity and handle redirection accordingly. – Jeel Vankhede Sep 24 '19 at 12:26
  • I'm sorry but when I reopen the app after deleting the account it doesn't notice the account is gone... I have the "mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged() on my onCreate() and "mAuth.addAuthStateListener(mAuthListener);" on my onStart(). Am I missing something?? – Pedro Marques Sep 24 '19 at 13:54
  • Well I guess I just found out... https://stackoverflow.com/a/35961217/5909648 – Pedro Marques Sep 24 '19 at 14:29

3 Answers3

3

You can listen to AuthStateListener for FirebaseUser's state changes.

Why?, basically when you remove user from server or other device, it would still be valid in your current device because of it's token is not refreshed yet locally.

Find out about more here.


Doc states that:

There are some cases where getCurrentUser will return a non-null FirebaseUser but the underlying token is not valid. This can happen, for example, if the user was deleted on another device and the local token has not refreshed. In this case, you may get a valid user getCurrentUser but subsequent calls to authenticated resources will fail.

getCurrentUser might also return null because the auth object has not finished initializing.

If you attach an AuthStateListener you will get a callback every time the underlying token state changes. This can be useful to react to edge cases like those mentioned above.

Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58
  • Thanks very much! I'll add that and see if it solves the problem! – Pedro Marques Sep 21 '19 at 12:56
  • I had the problem solved with your answer, then decided to separate the login and register in 2 activities. With that I also separated the createAccount() from signInWithEmailAndPassword() methods which made me add this "mAuth = FirebaseAuth.getInstance()" in both activities onCreate() method. In the logIn activity i added mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser currentUser = mAuth.getCurrentUser(); ... } }; but now doesn't work. Am I forgetting something or just can't do this? – Pedro Marques Sep 23 '19 at 23:46
  • Can you share the code in OP? I'll look into it and get back to you. – Jeel Vankhede Sep 24 '19 at 03:25
  • OP? I'm sorry I'm not getting there o.o' – Pedro Marques Sep 24 '19 at 11:18
2

For me, AuthStateListener didn't help me anymore. So I used work around, I removed the user from the realtime database and then I checked if he exists or not, If not then sign out like that:

DatabaseReference dbUsersRef = FirebaseDatabase.getInstance().getReference("Users");

dbUsersRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@com.google.firebase.database.annotations.NotNull DataSnapshot dataSnapshot) {
            if (!dataSnapshot.exists()){
                FirebaseAuth.getInstance().signOut();
                
                // user has sign out 
            } else {
                // user still logged in
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
Islam Ahmed
  • 668
  • 9
  • 19
0

seems like firebase saves user preferences locally try to clear the app and login again check this document FIREBASE USER AUTH

Black mamba
  • 462
  • 4
  • 15