Relate firebase Authetication to Realtime database

Asked

Viewed 243 times

1

I am creating an application, using firebase, in which the user performs a registration in firebase. I am using firebase authetication to create user by email/password and the Realtime database to save that user’s data. My problem is, I’m having trouble connecting these two databases. For example: when I create a user in Authentication firebase uses email as an identifier and tmb creates a user UID, in the Realtime database I use . push() to create a random node (or ID) for the user in the database. I wanted to use the person’s email as an ID in the Realtime database but cannot contain special characters in the node (@, ., '...) and tmb can’t get the user’s UID to use as an ID in the Realtime database.

I’ve tried to do

 usuarioReferencia.child(firebaseauth.getCurrentUser().getUid()).setValue(usuario);

but for some reason, this way, it takes the user’s UID registered BEFORE and not the current.

``` 

protected void onCreate(Bundle savedInstanceState) {
//Botão cadastrar - Faz o cadastro do user no firebase
        btnCadastrar = findViewById(R.id.btnCadastrar);
        btnCadastrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(checkFields() == 0){ //Verifica se todos os campos foram preenchidos
                    if(saveData() == true){ //se todos os campos foram preenchidos e foram salvos no banco de dados corretamente
                        createUser(); //método para criar usuário
                        Toast.makeText(getApplicationContext(),"Usuário criado com sucesso",Toast.LENGTH_LONG).show();
                        startActivity(new Intent(Cadastro.this, MainActivity.class)); //retorna para tela de login
                    } else{
                        Toast.makeText(getApplicationContext(),"E-mail e/ou senha não coincidem",Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(),"Há campos não preenchidos",Toast.LENGTH_LONG).show();
                }
            }
        });
    }´´´
    public void createUser(){
        firebaseauth.createUserWithEmailAndPassword(edtEmail.getText().toString(), edtSenha.getText().toString()).
                addOnCompleteListener(Cadastro.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){ //se usuario criado com sucesso
                    Log.i("createUser", "Usuário criado com sucesso");
                    Toast.makeText(getApplicationContext(),"Usuário criado com sucesso",Toast.LENGTH_LONG).show();
                } else{ //se der erro no cadastro
                    Log.i("createUser", "ERRO");
                    Toast.makeText(getApplicationContext(),"Erro. Usuário inválido",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}´´´

```//Salvar dados do usuário
    public boolean saveData(){
        Usuario usuario = new Usuario();

        usuario.setNome(edtNome.getText().toString());
        usuario.setTelefone(edtTel.getText().toString());
        usuario.setCelular(edtCel.getText().toString());
        usuario.setEmail(edtEmail.getText().toString());
        usuario.setSenha(edtSenha.getText().toString());

        //Verifica se o usuário é Cliente ou proprietário
        if(rbCliente.isChecked()){
            usuario.setTipo("Cliente");
        } else{
            usuario.setTipo("Proprietário");
        }
        //Verifica se o usuário é Homem ou Mulher
        if(rbFeminino.isChecked()){
            usuario.setSexo("Feminino");
        } else{
            usuario.setSexo("Masculino");
        }

        //Se os campos Email e Senha forem preenchidos corretamente
        if(checkEmail() == true && checkPassword() == true){
            firebaseauth.getCurrentUser().getUid(); //pega o UID do usuário

            usuarioReferencia.child(firebaseauth.getCurrentUser().getUid()).setValue(usuario); //salva dados no banco de dados firebase

            return true;
        } else{
            return false;
        }
    }´´´

1 answer

0

To use email as an ID you need to encode in Base64; and to create a user already has a method in firebase:

FirebaseAuth autentica;

private void cadastrarUsuario() {
        autentica = ConfiguracaoFirebase.getAutenticacao();
        autentica.createUserWithEmailAndPassword(
                mUsuario.getEmail(),mUsuario.getSenha()
        ).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(getApplicationContext(), getString(R.string.sucesso_cadastro), Toast.LENGTH_SHORT).show();
                    String novoUsuario = Base64Custom.codificarBase64(mUsuario.getEmail());
                    mUsuario.setId(novoUsuario);
                    mUsuario.salvar();

                    Preferencias preferencias = new Preferencias(CadastroUsuarioActivity.this);
                    preferencias.salvarDados(novoUsuario);

                    irParaTelaConversas();
                }
                else {
                    String erro_exception;
                    try {
                        throw task.getException();
                    } catch (FirebaseAuthWeakPasswordException e) {
                        erro_exception = "Digite uma senha mais forte!";
                    } catch (FirebaseAuthInvalidCredentialsException e ) {
                        erro_exception = "Email digitado é inválido!";
                    }catch (FirebaseAuthUserCollisionException e)
                    {
                        erro_exception = "Usuário já cadastrado !";
                    }
                    catch (Exception e) {
                        erro_exception = "Erro ao efetuar o cadastro!";
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), erro_exception, Toast.LENGTH_SHORT).show();
                }
            }
        });

Class Firebase Configuration:

public final class ConfiguracaoFirebase {

    private static DatabaseReference referenciaFireBase;
    private static FirebaseAuth auth;

    public static DatabaseReference getFirebase() {

        if(referenciaFireBase == null)
         referenciaFireBase  = FirebaseDatabase.getInstance().getReference();

        return referenciaFireBase;
    }

    public static FirebaseAuth getAutenticacao()
    {
        if(auth == null)
            auth = FirebaseAuth.getInstance();
        return auth;
    }
}

Base64custom:

public class Base64Custom {

    public static String codificarBase64(String texto) {
        return Base64.encodeToString(texto.getBytes(), Base64.DEFAULT).replaceAll("(\\n|\\r )", "");
    }

    public static String decodificarBase64(String textoDecodificado) {
        return new String(Base64.decode(textoDecodificado, Base64.DEFAULT));
    }

}

For more details follow the code of the project: github.com/jony5ds/whats_app_clone

Browser other questions tagged

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