如何从Android App中删除Firebase用户?

时间:2016-06-30 05:35:14

标签: android firebase-realtime-database firebase-authentication firebaseui

我正在尝试在我的Android应用中编写删除用户方法,但每次执行时都会遇到一些问题。当用户按下活动上的删除帐户按钮时,将执行此方法。我的应用适用于FirebaseUI Auth。

以下是方法:

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)当我执行该功能时,屏幕上会出现一个Smart Lock消息,并且用户再次登录。以下是此消息的屏幕截图。

Smartlock message

2)在其他情况下,当用户长时间登录时,该函数会抛出一个Exception,如下所示:

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 have to re-authenticate该用户,但在我使用Google登录时,我不确定该怎么做。

9 个答案:

答案 0 :(得分:17)

根据Firebase文档,用户delete()方法可以从 Firebase 中删除用户

在删除用户之前,请重新验证用户。

  

示例代码

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

   }
});

有关详情:https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user

如果您想要与其他单身提供商重新进行身份验证,则只需更改下面Provider GoogleAuthProvider的示例代码

GoogleAuthProvider.getCredential(googleIdToken,null);

答案 1 :(得分:3)

首先,您需要在用户登录时存储身份验证令牌或密码。如果您的应用无法提供诸如Google登录,Facebook登录或其他内容,那么您只需要存储密码。

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

答案 2 :(得分:3)

Ansuita Jr.提供的答案非常优美,并且仅存在一个小问题即可正确。 即使没有成功进行重新身份验证,用户也会被删除。 这是因为我们使用

  

user.delete()

始终执行的onComplete()方法中的

。 因此,我们需要添加一个if检查来检查任务是否成功,如下所述

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

答案 3 :(得分:2)

您的delete回调已经处理了失败的情况,为什么以后添加addOnFailureListener

尝试以这种方式删除它:

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

答案 4 :(得分:0)

使用此方法: -

删除()

相当于调用wine.holiday <- wine.sub2 %>% select(total, cdate) %>% subset(cdate>=2011-11-25, cdate<=2011-12-31) wine.holiday Source: local data frame [27,628 x 3] Groups: clubgroup_id.x [112] clubgroup_id.x total cdate (chr) (dbl) (date) 1 1 45 2011-10-04 2 1 45 2011-10-08 3 1 45 2011-10-09 4 1 45 2011-10-09 5 1 45 2011-10-11 6 1 45 2011-10-15 7 1 45 2011-10-24 8 1 90 2011-11-13 9 1 45 2011-11-18 10 1 45 2011-11-26 .. ... ... ...

<强> removeUser()

set(null)

答案 5 :(得分:0)

@Android开发人员:

我遇到一个问题,即在卸载应用程序后,Firebase身份验证信息仍保留在设备磁盘中。经过实验和阅读后,我发现在清单的android:allowBackup="false"标签中设置android:fullBackupContent="false"<application>可以确保在卸载应用程序后身份信息不会保留。

请注意,并非在所有Android设备上都存在这种持久性。实际上,它开始在我从未遇到过此问题的设备上发生。

答案 6 :(得分:0)

只有当前用户才能使用以下方法将其删除

user.delete();

,您也可以添加Oncompletelistner 由addind user.delete().addOnCompleteListner(new OnCompleteListner)和其他

答案 7 :(得分:0)

如果您使用的是 AuthUI FirebaseAuth ,则可以执行以下操作

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

 }

OR

FirebaseAuth.getInstance().currentUser.delete().addOnSuccessListener...

答案 8 :(得分:0)

如果登录方式是“匿名”,则可以直接调用

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

但如果是不同的方法,则需要重新进行身份验证。 How to re-authenticate