Cristian G
Cristian G

Reputation: 619

Android Firebase Facebook Authentication Logout function

I am using the facebook auth medthod with firebase and I can't figure out how to properly Log out a user. After I press the 'Continue with Facebook' button and give it access to my profile the button changes in 'Log out' and shows a dialog when I click it. The problem is that it doesn't actually log me out and the state is still signed in.

I found here how to log out the user from Firebase and Facebook in my app but I can't figure out where to put those 2 lines. I am looking for a Logout function or something like that.

I found here (different here) what might be my solution but it's pretty messy and can't understand. Can you please help me?

@Override
protected void onCreate(Bundle savedInstanceState) {
    mAuth = FirebaseAuth.getInstance();

    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);
    setContentView(R.layout.activity_login);

    mCallbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.e(TAG, "facebook:onSuccess:" + loginResult);
            handleFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            Log.e(TAG, "facebook:onCancel");
            // ...
        }

        @Override
        public void onError(FacebookException error) {
            Log.e(TAG, "facebook:onError", error);
            // ...
        }
    });

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());

                DatabaseReference myRef = database.getReference("Users");
                myRef.addValueEventListener(new ValueEventListener() {
                    boolean userExists = false;
                    User userFirebase;

                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot mydata : dataSnapshot.getChildren()){
                            userFirebase = mydata.getValue(User.class);

                            if(userFirebase.getEmail().equals(user.getEmail())){
                                Log.e(TAG, "User found in the database");
                                userExists = true;
                                Intent intent = new Intent(getBaseContext(), ActivityMain.class);
                                startActivity(intent);
                                break;
                            }
                        }

                        if (!userExists){
                            DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
                            mDatabase.child("Users").push().setValue(new User(user.getDisplayName(),user.getEmail(),0,0));

                            Intent intent = new Intent(getBaseContext(), ActivityMain.class);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                }); // checks if the user is in database and writes him if not

            } else {
                // User is signed out
                Log.e(TAG, "onAuthStateChanged:signed_out");
            }
        }
    };


}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Pass the activity result back to the Facebook SDK
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

private void handleFacebookAccessToken(AccessToken token) {
    Log.e(TAG, "handleFacebookAccessToken:" + token);

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.e(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.e(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(getBaseContext(), "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
}

Upvotes: 1

Views: 1635

Answers (1)

Hristo Stoyanov
Hristo Stoyanov

Reputation: 1960

You need to implement your own button and add and OnClickListener with the 2 methods mentioned :

Button logoutButton = (Button) findViewById(R.id.logout_button);
logoutButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        FirebaseAuth.getInstance().signOut();
        LoginManager.getInstance().logOut();
    }
});

You can't use the facebook logout button , because it only logs you out of facebook and you need the firebase logout aswell.

Upvotes: 4

Related Questions