Firebase Auth with Facebook - Save information to Realdatabase

Asked

Viewed 205 times

1

Guys, I’m using Firebaseuth to authenticate in my Android app with social networks like Facebook and Google, however, with Google Login I can do in addition to authenticate, save the returned user data, already with Facebook I can not do the same, I do the normal authentication, but I can’t retrieve the data to save in my Firebase database. Could someone help me?

Loginactivity.java

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

private EditText email;
private EditText senha;
private Button botaoLogar;
private Usuario usuario;

//Firebase
private FirebaseAuth autenticacao;
private DatabaseReference mUsersRef;
private FirebaseAuth.AuthStateListener mAuthListener;

private String TAG = "LoginActivity";

//Google
private GoogleApiClient googleApiClient;
private SignInButton signInButton;
public static final int SIGN_IN_CODE = 9991;
private ProgressDialog mProgressDialog;

//Facebook
private LoginButton btButtonFacebook;
private CallbackManager mCallBackManager;

//Progress Bar
ProgressBar progressBar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);


    //Verifica se o usuário já está logado
    verificarUsuarioLogado();



    email = (EditText) findViewById(R.id.edit_login_email);
    senha = (EditText) findViewById(R.id.edit_login_senha);
    botaoLogar = (Button) findViewById(R.id.bt_logar);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);

    //Facebook Controller
    mCallBackManager = CallbackManager.Factory.create();
    btButtonFacebook = (LoginButton) findViewById(R.id.btLoginFacebook);
    btButtonFacebook.setReadPermissions(Arrays.asList("email", "public_profile"));
    btButtonFacebook.registerCallback(mCallBackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "Facebook:onSucess:" + loginResult.getAccessToken().getUserId());
            handleFacebookAccessToken(loginResult.getAccessToken());

        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");

        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
        }
    });

    //Google Button
    signInButton = (SignInButton) findViewById(R.id.signBotaoGoogle);
    signInButton.setSize(SignInButton.SIZE_STANDARD);

    botaoLogar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            usuario = new Usuario();
            usuario.setEmail(email.getText().toString());
            usuario.setSenha(senha.getText().toString());
            validarLogin();
        }
    });

    signInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.signBotaoGoogle:
                    logarGoogleSignIn();
                    break;

            }
        }
    });

    //criando metodo de conexão Firebase para autenticação Google
    autenticacao = FirebaseAuth.getInstance();

    // Verificando se existe usuário logado //
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();

            if (user != null) {
                abrirTelaPrincipal();
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getDisplayName());

            } else {

                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
        }
    };

    // [START configure_signin]
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    // [END configure_signin]

    // [START build_client]
    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    // [END build_client]

}

//Facebook Controller Part-2

private void handleFacebookAccessToken(AccessToken token) {
    progressBar.setVisibility(View.VISIBLE);
    signInButton.setVisibility(View.GONE);
    btButtonFacebook.setVisibility(View.GONE);
    email.setVisibility(View.GONE);
    botaoLogar.setVisibility(View.GONE);
    senha.setVisibility(View.GONE);

    Log.d(TAG, "handleFacebookAccessToken:" + token);

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    autenticacao.signInWithCredential(credential)
            .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful() + task.getResult().getUser().getEmail());
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(LoginActivity.this, "Ocorreu um erro na autenticação com o Facebook, tente novamente",
                                Toast.LENGTH_SHORT).show();
                    }
                    progressBar.setVisibility(View.VISIBLE);
                    signInButton.setVisibility(View.GONE);
                    btButtonFacebook.setVisibility(View.GONE);
                    email.setVisibility(View.GONE);
                    botaoLogar.setVisibility(View.GONE);
                    senha.setVisibility(View.GONE);
                }

            });
}

// [START logarGoogleSignIn]
private void logarGoogleSignIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    startActivityForResult(signInIntent, SIGN_IN_CODE);
}
// [END logarGoogleSignIn]

// [START onActivityResult]
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
        mCallBackManager.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == SIGN_IN_CODE) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);

        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAutenticaGoogle(account);
            abrirTelaPrincipal();

        } else {
            Toast.makeText(this, "Erro ao logar com sua conta Google, tente novamente", Toast.LENGTH_LONG).show();
        }
    }
}
// [END onActivityResult]

@Override
public void onStart() {
    super.onStart();
    autenticacao.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        autenticacao.removeAuthStateListener(mAuthListener);
    }
}

// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount contaGoogle = result.getSignInAccount();

        usuario = new Usuario();
        usuario.setId(contaGoogle.getId());
        usuario.setNome(contaGoogle.getDisplayName());
        usuario.setEmail(contaGoogle.getEmail());
        usuario.setProvider("google");
        usuario.salvar();

        Log.d(TAG, "TesteContaGoogle:" + usuario.getId() + usuario.getNome() + usuario.getEmail() );

    } else {
        // Signed out, show unauthenticated UI.

    }
}
// [END handleSignInResult]

private void firebaseAutenticaGoogle(GoogleSignInAccount contaGoogleRecuperada) {
    progressBar.setVisibility(View.VISIBLE);
    signInButton.setVisibility(View.GONE);
    btButtonFacebook.setVisibility(View.GONE);
    email.setVisibility(View.GONE);
    botaoLogar.setVisibility(View.GONE);
    senha.setVisibility(View.GONE);

    Log.d(TAG, "firebaseAutenticaGoogle:" + contaGoogleRecuperada.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(contaGoogleRecuperada.getIdToken(), null);
    autenticacao.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull final Task<AuthResult> task) {
                    Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.                        //

                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInWithCredential", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                    progressBar.setVisibility(View.VISIBLE);
                    signInButton.setVisibility(View.GONE);
                    btButtonFacebook.setVisibility(View.GONE);
                    email.setVisibility(View.GONE);
                    botaoLogar.setVisibility(View.GONE);
                    senha.setVisibility(View.GONE);
                }
            });
}

//Recuperando usuario Facebook


public void abrirCadastroUsuario(View view){

    Intent intent = new Intent(LoginActivity.this, CadastroUsuarioActivity.class);
    startActivity( intent );

}

private void validarLogin(){

    autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
    autenticacao.signInWithEmailAndPassword(
            usuario.getEmail(),
            usuario.getSenha()
    ).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            if( task.isSuccessful() ){
                abrirTelaPrincipal();
                Toast.makeText(LoginActivity.this, "Sucesso ao fazer login!", Toast.LENGTH_LONG ).show();
            }else{
                Toast.makeText(LoginActivity.this, "Erro ao fazer login!", Toast.LENGTH_LONG ).show();
            }

        }
    });
}

private void abrirTelaPrincipal(){
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity( intent );
    finish();
}

private void verificarUsuarioLogado(){
    autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
    if( autenticacao.getCurrentUser() != null ){
        abrirTelaPrincipal();
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

}

No answers

Browser other questions tagged

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