Delete a user from firebase Auth when an Activity is destroyed

Asked

Viewed 419 times

0

I have an activity call ValidadorActivity, in this Activity I do a validation by SMS, right after the user registers.

The register is made by Firebase Auth however is done before this validation, so I look for a way to delete the Firebase record when the user leaves the validation screen without putting the Token that was sent by SMS correctly.

   @Override
    protected void onDestroy() {
        super.onDestroy();

        //Ao fechar completamente a tela de validação com o campo textValidacao nulo ou incorreto, o cadastro no autenticacao e no banco de dados sao apagados, para evitar o cadastro de usuarios não validados.

        String codigoDigitado = codigoValidacao.getText().toString(); //Pega o texto da caixa de texto

        if (! codigoDigitado.equals(tokenGerado)) {//Verifica se esse texto e igual

            user.delete().addOnCompleteListener(new OnCompleteListener<Void>() { //deleta o usuario no Auth
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    if (task.isSuccessful()) {//Testa para ver se funcionou

                        Log.i("Usuario deletado(auth)","Sim");


                    }else{

                        Log.i("Usuario deletado(auth)","Não");

                    }

                }
            });
}

But it is not deleting, I believe the code is right. Any idea or suggestion?

1 answer

1

Opa, blza!?

It will be on onDestroy itself, but before deleting a user you need to authenticate it again, then take the data from the previous Activity and pass to this:

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

     // Obtenha credenciais de autenticação do usuário para nova autenticação. O exemplo abaixo mostra
     // credenciais de e-mail e senha, mas há vários provedores possíveis,
     // como GoogleAuthProvider ou FacebookAuthProvider.
    AuthCredential credential = EmailAuthProvider
            .getCredential("[email protected]", "password1234");

    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, "Conta deletada");
                }
            }
        });

   }
});

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

If you want the user authentication to be with another Singin server, you need to change the Provider to Googleauthprovider. Following an example code:

GoogleAuthProvider.getCredential(googleIdToken,null);
  • Let me get this straight... because of onDrestroy, I have to re-authenticate the user to delete, because I used that same code on a button and it worked normally. So the reason I need to re-authenticate the user is because I am destroying Activity?

  • Important: In order to be able to delete a user, it needs to have logged in recently. See the article Re-user.

  • This information is in the documentation, it is necessary to guarantee a recent access to it so you can delete it: see in this topic of the documentation: https://firebase.google.com/docs/auth/android/manage-users#delete_a_user

  • So in case, he just logged in, right after he logs in, he falls on that screen q is a check screen, and then test if the token generated is equal and tals

  • Dude, I ran a test here, and he’s not even going through the code snippet when I close Activity. I click to open all the applications and then close it but the code has in Destroy nor runs!

  • Because of the doubts, pass as parameter the user and password, in onDestroy, put the code before super.onDestroy Put a debug in the application, when minimize, it stops in onPause but when you close it, it falls in onDestroy

  • So after doing several tests I discovered that onDestroy is only activated when Activity is shut down by the system, not when you force it to close, for example when you press the direct button and drag it to close, someone would have some way to access this code whenever Activity was closed?

  • What you can do is the following, saves the status that is found in the android sharedPreference. If it closes the App or kills the activity, on onCreate and onRestart you check the status of the account (pending, effective, not started, null, sla will depend on your case). case of pending you will be able to delete the user and mount the screen again to do the procedure again.

  • Man thought about it, but wanted a solution this way. But thanks man, I’m thinking I’ll need to do it this way anyway! Obg!

  • I’ve done something similar, in case I need to have the code here to record and recover in sharedPreferences

  • Thank you! I have the code here tbm.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.