26

I'm trying to code a Delete User method in my Android App, but I have some issues each time I execute it. This method will be executed when a user pushes the Delete account button on an Activity. My apps works with FirebaseUI Auth.

Here is the method:

private void deleteAccount() {
    Log.d(TAG, "ingreso a deleteAccount");
    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    final FirebaseUser currentUser = firebaseAuth.getCurrentUser();

    currentUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG,"OK! Works fine!");
                startActivity(new Intent(Main3WelcomeActivity.this, Main3Activity.class));
                finish();
            } 
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG,"Ocurrio un error durante la eliminación del usuario", e);
        }
    });
}

1) When I execute that function a Smart Lock message appears on the screen and the user is signed in again. Here is a screenshot of this message.

Smartlock message

2) On other occasions, when the user is logged in for a long time, the function throws an Exception like this:

06-30 00:01:26.672 11152-11152/com.devpicon.android.firebasesamples E/Main3WelcomeActivity: Ocurrio un error durante la eliminación del usuario
com.google.firebase.FirebaseException: An internal error has occured. [ CREDENTIAL_TOO_OLD_LOGIN_AGAIN ]
at com.google.android.gms.internal.zzacq.zzbN(Unknown Source)
at com.google.android.gms.internal.zzacn$zzg.zza(Unknown Source)
at com.google.android.gms.internal.zzacy.zzbO(Unknown Source)
at com.google.android.gms.internal.zzacy$zza.onFailure(Unknown Source)
at com.google.android.gms.internal.zzact$zza.onTransact(Unknown Source)
at android.os.Binder.execTransact(Binder.java:453)

I've read that I have to re-authenticate the user but I'm not sure how to do this when I'm working with Google Sign In.

Darren Shewry
  • 10,179
  • 4
  • 50
  • 46
Armando
  • 583
  • 2
  • 7
  • 16

10 Answers10

32

As per the Firebase documentation can user delete() method to remove user from the Firebase

Before remove the user please reAuthenticate the user.

Sample code

     final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        // Get auth credentials from the user for re-authentication. The example below shows
        // email and password credentials but there are multiple possible providers,
        // such as GoogleAuthProvider or FacebookAuthProvider.
        AuthCredential credential = EmailAuthProvider
                .getCredential("user@example.com", "password1234");

        // Prompt the user to re-provide their sign-in credentials
        user.reauthenticate(credential)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
           user.delete()
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "User account deleted.");
                    }
                }
            });

   }
});

For more details : https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user

If you want to user re Authentication with other singin provider only need to change the Provider for GoogleAuthProvider below is the sample code

GoogleAuthProvider.getCredential(googleIdToken,null);
Maheshwar Ligade
  • 6,709
  • 4
  • 42
  • 59
6

The answer provided by Ansuita Jr. is very beautifully explained and is correct with just a small problem. The user gets deleted even without having successful re-authentication. This is because we use

user.delete()

in the onComplete() method which is always executed. Therefore, we need to add an if check to check whether the task is successful or not which is mentioned below

user.reauthenticate(credential)
          .addOnCompleteListener(new OnCompleteListener<Void>() {
             @Override
             public void onComplete(@NonNull Task<Void> task) {
                 if (task.isSuccessful()) {
                    Log.e("TAG", "onComplete: authentication complete");
                    user.delete()
                    .addOnCompleteListener (new OnCompleteListener<Void>() {
                           @Override
                           public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    Log.e("TAG", "User account deleted.");
                                } else {
                                    Log.e("TAG", "User account deletion unsucessful.");
                                }
                          }
                     });
                 } else {
                     Toast.makeText(UserProfileActivity.this, "Authentication failed", 
                               Toast.LENGTH_SHORT).show();
                 }
              }
         });
Damanpreet Singh
  • 678
  • 10
  • 15
3

Your delete callback already handles the case of a failure, why do you add addOnFailureListener later?

Try to delete it, this way:

private void deleteAccount() {
    Log.d(TAG, "ingreso a deleteAccount");
    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    final FirebaseUser currentUser = firebaseAuth.getCurrentUser();
    currentUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Log.d(TAG,"OK! Works fine!");
                startActivity(new Intent(Main3WelcomeActivity.this, Main3Activity.class));
                finish();
            } else {
                Log.w(TAG,"Something is wrong!");
            }
        }
    });
}
Ami Hollander
  • 2,435
  • 3
  • 29
  • 47
3

First of all, you need to store the auth token or the password at the moment your user is logging in. If your app doesn't provide such as Google Sign-in, Facebook Sign-in or others, you just need to store the password.

//If there's any, delete all stored content from this user on Real Time Database. 
yourDatabaseReferenceNode.removeValue();

//Getting the user instance.
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

if (user != null) {
    //You need to get here the token you saved at logging-in time.
    String token = "userSavedToken";
    //You need to get here the password you saved at logging-in time.
    String password = "userSavedPassword";

    AuthCredential credential;

    //This means you didn't have the token because user used like Facebook Sign-in method.
    if (token == null) {
       credential = EmailAuthProvider.getCredential(user.getEmail(), password);
    } else {
       //Doesn't matter if it was Facebook Sign-in or others. It will always work using GoogleAuthProvider for whatever the provider.
       credential = GoogleAuthProvider.getCredential(token, null);
    }

    //We have to reauthenticate user because we don't know how long 
    //it was the sign-in. Calling reauthenticate, will update the 
    //user login and prevent FirebaseException (CREDENTIAL_TOO_OLD_LOGIN_AGAIN) on user.delete()
    user.reauthenticate(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        //Calling delete to remove the user and wait for a result.
                        user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    //Ok, user remove
                                } else {
                                    //Handle the exception
                                    task.getException();
                                }
                            }
                        });
                    }
                });    
}        
Vansuita Jr.
  • 1,949
  • 17
  • 18
  • Sir, I want to delete who authenticated right now. I mean user logged in my app and decide to delete his/her account. How I can do that? – Yunus Haznedar Apr 10 '17 at 14:27
  • Great answer and comment explanation for multi-provider authentication. – Jantzilla Nov 10 '18 at 18:00
  • @Vansuita Jr. this works but when i reauthenticate then its work with invalid password also that should not the case – MARSH May 04 '23 at 06:31
1

@Android developers:

I faced an issue where the Firebase Auth information was persisting in the device's disk AFTER uninstalling the app. After experimenting and reading about it, I found that setting android:allowBackup="false" and android:fullBackupContent="false" in the Manifest's <application> tag will ensure the identity information is not persisted after the app is uninstalled.

Please note, this kind of persistence was not happening on all Android devices. In fact, it started happening on one of my devices that never had this issue.

Ram Iyer
  • 1,621
  • 1
  • 23
  • 25
1

If the sign-in method is "Anonymous", you can just call

FirebaseAuth.getInstance().getCurrentUser().delete().addOnCompleteListener(task -> {
                       if (task.isSuccessful()){
                           Log.d(TAG, "Deletion Success");
                       }
                    });

But if it's a different method, you will need a re-authentication. How to re-authenticate

Dharman
  • 30,962
  • 25
  • 85
  • 135
avs
  • 122
  • 1
  • 12
0

Use this methods :-

remove()

is equivalent to calling set(null).

or

removeUser()

removeUser(credentials, [onComplete])
0

Only get current user and delete it by using following method it'll work fine

user.delete();

and you can add on Oncompletelistner also by addinduser.delete().addOnCompleteListner(new OnCompleteListner)and more on

rajeev ranjan
  • 222
  • 4
  • 10
0

If you are using AuthUI or FirebaseAuth you can just do the following

 AuthUI.getInstance().delete(context).addOnSuccessListener {
           
 }.addOnFailureListener{

 }

OR

FirebaseAuth.getInstance().currentUser.delete().addOnSuccessListener...
Ronny Shibley
  • 2,030
  • 22
  • 25
0

If you are using FirebaseUI Auth you can just do the following

private void delete() {
    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    FirebaseUser user=firebaseAuth.getCurrentUser();
    user.delete()
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()){
                        startActivity(new Intent(Main3WelcomeActivity.this, Main3Activity.class));
                        finish();
                        Toast.makeText(Main3WelcomeActivity.this,"Account deleted",Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(Home.this,"failed",Toast.LENGTH_LONG).show();

                    }

                }
            });}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 16 '22 at 11:56