Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package teles.developer.com.mangalist.View.Activity;
- import android.app.ProgressDialog;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.graphics.Typeface;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.net.Uri;
- import android.os.Bundle;
- import android.support.annotation.NonNull;
- import android.support.design.widget.Snackbar;
- import android.support.design.widget.TextInputLayout;
- import android.support.v4.app.DialogFragment;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.View;
- import android.view.WindowManager;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.facebook.AccessToken;
- import com.facebook.CallbackManager;
- import com.facebook.FacebookCallback;
- import com.facebook.FacebookException;
- import com.facebook.login.LoginResult;
- import com.facebook.login.widget.LoginButton;
- import com.google.android.gms.auth.api.Auth;
- import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
- import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
- import com.google.android.gms.auth.api.signin.GoogleSignInResult;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.SignInButton;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.tasks.OnCompleteListener;
- import com.google.android.gms.tasks.Task;
- import com.google.firebase.auth.AuthCredential;
- import com.google.firebase.auth.AuthResult;
- import com.google.firebase.auth.FacebookAuthProvider;
- import com.google.firebase.auth.FirebaseAuth;
- import com.google.firebase.auth.FirebaseUser;
- import com.google.firebase.auth.GoogleAuthProvider;
- import com.google.firebase.crash.FirebaseCrash;
- import teles.developer.com.mangalist.Model.User;
- import teles.developer.com.mangalist.R;
- import teles.developer.com.mangalist.Services.api.Services;
- import teles.developer.com.mangalist.Services.listeners.GenericListener;
- import teles.developer.com.mangalist.Utils.AlertUtils;
- import teles.developer.com.mangalist.View.DialogFragment.CadastroDialog;
- public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
- private static final String TAG = "Login";
- private TextView txt, cadastre_aqui;
- private Button entrar;
- private static final int RC_SIGN_IN = 9001;
- private Services mService = new Services();
- private EditText email, senha;
- ProgressDialog progress;
- SharedPreferences sharedPreferences;
- SharedPreferences.Editor editor;
- //TODO preciso atualizar os idiomas com as mensagens novas de login
- //TODO modificar playstore com vários idiomas
- /* *************************************
- * FIREBASE *
- ***************************************/
- /* Data from the authenticated user */
- private FirebaseAuth mAuth;
- /* Listener for Firebase session changes */
- private FirebaseAuth.AuthStateListener mAuthListener;
- /* *************************************
- * GOOGLE *
- ***************************************/
- private GoogleApiClient mGoogleApiClient;
- public SignInButton signInButton;
- /* *************************************
- * FACEBOOK *
- ***************************************/
- /* The login button for Facebook */
- private LoginButton loginButton;
- /* The callback manager for Facebook */
- private CallbackManager mCallbackManager;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- //Retira status bar
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
- setContentView(R.layout.activity_login);
- sharedPreferences = getSharedPreferences("ID_UNICO", Context.MODE_PRIVATE);
- editor = sharedPreferences.edit();
- txt = (TextView) findViewById(R.id.textview_mangalist);
- cadastre_aqui = (TextView) findViewById(R.id.textview_cadastre_aqui);
- email = (EditText) findViewById(R.id.edittext_usuario_login_principal);
- senha = (EditText) findViewById(R.id.edittext_usuario_senha);
- entrar = (Button) findViewById(R.id.login_entrar);
- progress = new ProgressDialog(this);
- progress.setMessage("Carregando...");
- progress.setIndeterminate(true);
- //Colocar uma fonte diferente no textview
- Typeface type = Typeface.createFromAsset(getAssets(), "fonts/Komika_display.ttf");
- txt.setTypeface(type);
- /* *************************************
- * GOOGLE *
- ***************************************/
- signInButton = (SignInButton) findViewById(R.id.sign_in_button);
- // [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.requestIdToken))
- .requestEmail()
- .requestProfile()
- .build();
- // [END configure_signin]
- // [START build_client]
- // Build a GoogleApiClient with access to the Google Sign-In API and the
- // options specified by gso.
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .enableAutoManage(this, this)
- .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
- .build();
- // [END build_client]
- // signInButton.setSize(SignInButton.SIZE_STANDARD);
- /* *************************************
- * FACEBOOK *
- ***************************************/
- facebookCall();
- mAuth = FirebaseAuth.getInstance();
- firebaseCall();
- listenersButtons();
- }
- private void signIn() {
- Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
- startActivityForResult(signInIntent, RC_SIGN_IN);
- }
- /**
- * Método que inclui login com facebook
- */
- private void facebookCall() {
- }
- /**
- * Método que ligo o resultado do facebook ao login do Firebase
- * com sucesso, no método de retorno de chamada onSuccess do LoginButton,
- * obtenha um token de acesso para o usuário conectado,
- * troque-o por uma credencial do Firebase e autentique com o Firebase usando essa credencial:
- *
- * @param token
- */
- private void handleFacebookAccessToken(AccessToken token) {
- Log.d(TAG, "handleFacebookAccessToken:" + token);
- AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull 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();
- }
- }
- });
- }
- /**
- * Método que ligo o resultado do Google ao login do Firebase
- * com sucesso, no método de retorno de chamada onSuccess do LoginButton,
- * obtenha um token de acesso para o usuário conectado,
- * troque-o por uma credencial do Firebase e autentique com o Firebase usando essa credencial:
- *
- * @param acct
- */
- private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
- Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
- AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull 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. gg",
- Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
- /**
- * Call firebase e inicia o listener
- */
- private void firebaseCall() {
- mAuthListener = new FirebaseAuth.AuthStateListener() {
- @Override
- public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
- FirebaseUser user = firebaseAuth.getCurrentUser();
- if (user != null) {
- // User is signed in
- String name = user.getDisplayName();
- String email = user.getEmail();
- Uri photoUrl = user.getPhotoUrl();
- String photo = photoUrl.toString();
- cadastraNoBancoComRedeSocial(name, email, photo);
- Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
- } else {
- // User is signed out
- Log.d(TAG, "onAuthStateChanged:signed_out");
- }
- }
- };
- }
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- progress.show();
- // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
- if (requestCode == RC_SIGN_IN) {
- GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
- String aqui = result.getStatus().getStatusMessage();
- if (result.isSuccess()) {
- // Google Sign In was successful, authenticate with Firebase
- GoogleSignInAccount account = result.getSignInAccount();
- firebaseAuthWithGoogle(account);
- } else {
- // Google Sign In failed, update UI appropriately
- int x = 1;
- }
- } else {
- //Facebook
- mCallbackManager.onActivityResult(requestCode, resultCode, data);
- }
- }
- @Override
- public void onStart() {
- super.onStart();
- mAuth.addAuthStateListener(mAuthListener);
- }
- @Override
- public void onStop() {
- super.onStop();
- if (mAuthListener != null) {
- mAuth.removeAuthStateListener(mAuthListener);
- }
- }
- /**
- * Chama os listeners para os botões
- */
- public void listenersButtons() {
- entrar.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (isNetworkAvailable()) {
- getDadosUser();
- } else {
- Snackbar.make(findViewById(android.R.id.content), getString(R.string.string_internetmsg), Snackbar.LENGTH_SHORT).show();
- }
- }
- });
- signInButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (isNetworkAvailable()) {
- signIn();
- } else {
- Snackbar.make(findViewById(android.R.id.content), getString(R.string.string_internetmsg), Snackbar.LENGTH_SHORT).show();
- }
- }
- });
- cadastre_aqui.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- callDialogCadastro();
- }
- });
- }
- private void getDadosUser() {
- String e_mail = email.getText().toString();
- String password = senha.getText().toString();
- if (e_mail.matches("")) {
- AlertUtils.makeToastShort(getApplicationContext(), "Coloque seu email por favor");
- } else {
- if (password.matches("")) {
- AlertUtils.makeToastShort(getApplicationContext(), "Coloque uma descrição por favor");
- } else {
- if (!e_mail.contains("@")||e_mail.length() < 7) {
- AlertUtils.makeToastShort(getApplicationContext(), "Colque um e-mail válido");
- } else {
- if (password.length() < 6) {
- AlertUtils.makeToastShort(getApplicationContext(), "Senha deve ter 6 dígitos ou mais");
- } else {
- fazLoginComum(e_mail, password);
- progress.show();
- }
- }
- }
- }
- }
- /**
- * Faz o login comum no sistema.
- * @param email
- * @param password
- */
- private void fazLoginComum(String email, String password) {
- //Se o resultado for um status de que o cara está no banco, dai faz login automatico
- mService.loginComum(this, email, password, new GenericListener<User>() {
- @Override
- public void gotGenericSuccess(User response) {
- setModel(response);
- }
- @Override
- public void showErrorMessage(String message) {
- progress.dismiss();
- AlertUtils.makeToast(getApplicationContext(), message);
- }
- @Override
- public void gotGenericsFailure(String message) {
- progress.dismiss();
- AlertUtils.makeToast(getApplicationContext(), message);
- }
- });
- }
- /**
- * Chama um dialog para fazer cadastro comum.
- */
- public void callDialogCadastro() {
- DialogFragment novoDialogo = new CadastroDialog();
- novoDialogo.show(this.getSupportFragmentManager(), "TAG");
- }
- /**
- * Acessa o banco e cadastra no servidor os dados do usuário. Infos vindas de rede social.
- *
- * @param name
- * @param email
- * @param photoUrl
- */
- public void cadastraNoBancoComRedeSocial(String name, String email, String photoUrl) {
- //Se o resultado for um status de que o cara está no banco, dai faz login automatico
- mService.cadastrarUserRS(this, email, name, photoUrl, new GenericListener<User>() {
- @Override
- public void gotGenericSuccess(User response) {
- setModel(response);
- }
- @Override
- public void showErrorMessage(String message) {
- progress.dismiss();
- AlertUtils.makeToast(getApplicationContext(), message);
- }
- @Override
- public void gotGenericsFailure(String message) {
- progress.dismiss();
- AlertUtils.makeToast(getApplicationContext(), message);
- }
- });
- }
- /**
- * Método que seta o model com as infos.
- * @param response
- */
- private void setModel(User response) {
- if (response != null && response.getUid() != null) {
- salvaDadosUserLocal(response.getName(), response.getEmail(), response.getUid(), response.getProfile_image());
- iniciaMain();
- } else //must be error object
- {
- AlertUtils.makeToast(getApplicationContext(), "Erro ao fazer o login. Confira e-mail e senha e tente novamente.");
- progress.dismiss();
- }
- }
- /**
- * Método que inicia a main.
- */
- private void iniciaMain() {
- progress.dismiss();
- Intent intent = new Intent(this, MainActivity.class);
- startActivity(intent);
- this.finish();
- }
- /**
- * Salva usuário em sharedPreference.
- *
- * @param nomeUsuario
- * @param emailUsuario
- * @param id_Usuario
- * @param fotoUsuario
- */
- public void salvaDadosUserLocal(String nomeUsuario, String emailUsuario, String id_Usuario, String fotoUsuario) {
- editor.putString("nomeUsuario", nomeUsuario);
- editor.putString("emailUsuario", emailUsuario);
- editor.putString("idUsuario", id_Usuario);
- editor.putString("fotoUsuario", fotoUsuario);
- editor.commit();
- }
- /**
- * Verificação se a network está ativa
- *
- * @return
- */
- public boolean isNetworkAvailable() {
- ConnectivityManager connectivityManager =
- (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetworkInfo = connectivityManager
- .getActiveNetworkInfo();
- return activeNetworkInfo != null;
- }
- @Override
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
- // An unresolvable error has occurred and Google APIs (including Sign-In) will not
- // be available.
- Log.d(TAG, "onConnectionFailed:" + connectionResult);
- }
- }
Add Comment
Please, Sign In to add comment