How to delete a Firebase user from Android App?

北城余情 提交于 2019-12-03 01:41:28

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);

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();
                 }
              }
         });

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();
                                }
                            }
                        });
                    }
                });    
}        

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!");
            }
        }
    });
}

Use this methods :-

remove()

is equivalent to calling set(null).

or

removeUser()

removeUser(credentials, [onComplete])

@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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!