How to delete a Firebase user from Android App?
Solution 1
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("[email protected]", "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);
Solution 2
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();
}
}
});
Solution 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();
}
}
});
}
});
}
Solution 4
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!");
}
}
});
}
Solution 5
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
Related videos on Youtube
Comments
-
Armando almost 2 years
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.
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.
-
Maheshwar Ligade almost 8 yearsuse removeUser({credentials}) to it
-
-
Armando almost 8 yearsSure, but I don't know how to do the same with GoogleSignInProvider.
-
Maheshwar Ligade almost 8 yearsyou have to fallow the same steps AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken,null); and all other steps are same
-
Yunus Haznedar about 7 yearsBut, how can I know the user's password. Is there any method for that?
-
Yunus Haznedar about 7 yearsSir, 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?
-
Maheshwar Ligade about 7 yearsfirebase.google.com/docs/auth/web/manage-users this link may useful
-
Yunus Haznedar about 7 yearsThanks sir. But I wanna ask you one more question. This code you showed us, can delete a Facebook user too?
-
Maheshwar Ligade about 7 yearsthis will delete user from firebase DB, if Facebook user authentication data in firebase then it might delete I haven't tried but if we consider general behavior this might get deleted
-
Yunus Haznedar almost 7 yearsOkay, this is so weird, how can I know user's password?
-
Pratik Butani over 5 yearsIs it possible to delete other users from one user? as you are using
currentUser
object for Currently Logged-in user only. -
Jantzilla over 5 yearsGreat answer and comment explanation for multi-provider authentication.
-
M Umer over 4 years@PratikButani no it is not possible.