Guest User

Untitled

a guest
Jul 11th, 2017
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.18 KB | None | 0 0
  1. package teles.developer.com.mangalist.View.Activity;
  2.  
  3. import android.app.ProgressDialog;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.SharedPreferences;
  7. import android.graphics.Typeface;
  8. import android.net.ConnectivityManager;
  9. import android.net.NetworkInfo;
  10. import android.net.Uri;
  11. import android.os.Bundle;
  12. import android.support.annotation.NonNull;
  13. import android.support.design.widget.Snackbar;
  14. import android.support.design.widget.TextInputLayout;
  15. import android.support.v4.app.DialogFragment;
  16. import android.support.v7.app.AppCompatActivity;
  17. import android.util.Log;
  18. import android.view.View;
  19. import android.view.WindowManager;
  20. import android.widget.Button;
  21. import android.widget.EditText;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24.  
  25. import com.facebook.AccessToken;
  26. import com.facebook.CallbackManager;
  27. import com.facebook.FacebookCallback;
  28. import com.facebook.FacebookException;
  29. import com.facebook.login.LoginResult;
  30. import com.facebook.login.widget.LoginButton;
  31. import com.google.android.gms.auth.api.Auth;
  32. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
  33. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
  34. import com.google.android.gms.auth.api.signin.GoogleSignInResult;
  35. import com.google.android.gms.common.ConnectionResult;
  36. import com.google.android.gms.common.SignInButton;
  37. import com.google.android.gms.common.api.GoogleApiClient;
  38. import com.google.android.gms.tasks.OnCompleteListener;
  39. import com.google.android.gms.tasks.Task;
  40. import com.google.firebase.auth.AuthCredential;
  41. import com.google.firebase.auth.AuthResult;
  42. import com.google.firebase.auth.FacebookAuthProvider;
  43. import com.google.firebase.auth.FirebaseAuth;
  44. import com.google.firebase.auth.FirebaseUser;
  45. import com.google.firebase.auth.GoogleAuthProvider;
  46. import com.google.firebase.crash.FirebaseCrash;
  47.  
  48. import teles.developer.com.mangalist.Model.User;
  49. import teles.developer.com.mangalist.R;
  50. import teles.developer.com.mangalist.Services.api.Services;
  51. import teles.developer.com.mangalist.Services.listeners.GenericListener;
  52. import teles.developer.com.mangalist.Utils.AlertUtils;
  53. import teles.developer.com.mangalist.View.DialogFragment.CadastroDialog;
  54.  
  55. public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
  56.  
  57.     private static final String TAG = "Login";
  58.     private TextView txt, cadastre_aqui;
  59.     private Button entrar;
  60.     private static final int RC_SIGN_IN = 9001;
  61.     private Services mService = new Services();
  62.     private EditText email, senha;
  63.     ProgressDialog progress;
  64.  
  65.     SharedPreferences sharedPreferences;
  66.     SharedPreferences.Editor editor;
  67.  
  68.     //TODO preciso atualizar os idiomas com as mensagens novas de login
  69.  
  70.     //TODO modificar playstore com vários idiomas
  71.  
  72.     /* *************************************
  73.      *              FIREBASE               *
  74.      ***************************************/
  75.  
  76.     /* Data from the authenticated user */
  77.     private FirebaseAuth mAuth;
  78.  
  79.     /* Listener for Firebase session changes */
  80.     private FirebaseAuth.AuthStateListener mAuthListener;
  81.  
  82.      /* *************************************
  83.      *              GOOGLE                 *
  84.      ***************************************/
  85.  
  86.     private GoogleApiClient mGoogleApiClient;
  87.     public SignInButton signInButton;
  88.  
  89.  
  90.     /* *************************************
  91.      *              FACEBOOK               *
  92.      ***************************************/
  93.  
  94.     /* The login button for Facebook */
  95.     private LoginButton loginButton;
  96.  
  97.     /* The callback manager for Facebook */
  98.     private CallbackManager mCallbackManager;
  99.  
  100.     @Override
  101.     protected void onCreate(Bundle savedInstanceState) {
  102.         super.onCreate(savedInstanceState);
  103.  
  104.         //Retira status bar
  105.         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
  106.         setContentView(R.layout.activity_login);
  107.  
  108.         sharedPreferences = getSharedPreferences("ID_UNICO", Context.MODE_PRIVATE);
  109.         editor = sharedPreferences.edit();
  110.  
  111.  
  112.         txt = (TextView) findViewById(R.id.textview_mangalist);
  113.         cadastre_aqui = (TextView) findViewById(R.id.textview_cadastre_aqui);
  114.         email = (EditText) findViewById(R.id.edittext_usuario_login_principal);
  115.         senha = (EditText) findViewById(R.id.edittext_usuario_senha);
  116.         entrar = (Button) findViewById(R.id.login_entrar);
  117.  
  118.  
  119.         progress = new ProgressDialog(this);
  120.         progress.setMessage("Carregando...");
  121.         progress.setIndeterminate(true);
  122.  
  123.  
  124.         //Colocar uma fonte diferente no textview
  125.         Typeface type = Typeface.createFromAsset(getAssets(), "fonts/Komika_display.ttf");
  126.         txt.setTypeface(type);
  127.  
  128.         /* *************************************
  129.         *              GOOGLE                 *
  130.          ***************************************/
  131.  
  132.         signInButton = (SignInButton) findViewById(R.id.sign_in_button);
  133.  
  134.         // [START configure_signin]
  135.         // Configure sign-in to request the user's ID, email address, and basic
  136.         // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
  137.         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  138.                 .requestIdToken(getString(R.string.requestIdToken))
  139.                 .requestEmail()
  140.                 .requestProfile()
  141.                 .build();
  142.         // [END configure_signin]
  143.  
  144.         // [START build_client]
  145.         // Build a GoogleApiClient with access to the Google Sign-In API and the
  146.         // options specified by gso.
  147.         mGoogleApiClient = new GoogleApiClient.Builder(this)
  148.                 .enableAutoManage(this, this)
  149.                 .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
  150.                 .build();
  151.         // [END build_client]
  152.  
  153.  
  154. //        signInButton.setSize(SignInButton.SIZE_STANDARD);
  155.  
  156.  
  157.         /* *************************************
  158.         *              FACEBOOK                 *
  159.          ***************************************/
  160.         facebookCall();
  161.  
  162.         mAuth = FirebaseAuth.getInstance();
  163.  
  164.         firebaseCall();
  165.  
  166.         listenersButtons();
  167.  
  168.     }
  169.  
  170.  
  171.     private void signIn() {
  172.         Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
  173.         startActivityForResult(signInIntent, RC_SIGN_IN);
  174.     }
  175.  
  176.     /**
  177.      * Método que inclui login com facebook
  178.      */
  179.     private void facebookCall() {
  180.  
  181.     }
  182.  
  183.     /**
  184.      * Método que ligo o resultado do facebook ao login do Firebase
  185.      * com sucesso, no método de retorno de chamada onSuccess do LoginButton,
  186.      * obtenha um token de acesso para o usuário conectado,
  187.      * troque-o por uma credencial do Firebase e autentique com o Firebase usando essa credencial:
  188.      *
  189.      * @param token
  190.      */
  191.     private void handleFacebookAccessToken(AccessToken token) {
  192.         Log.d(TAG, "handleFacebookAccessToken:" + token);
  193.  
  194.         AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
  195.         mAuth.signInWithCredential(credential)
  196.                 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  197.                     @Override
  198.                     public void onComplete(@NonNull Task<AuthResult> task) {
  199.                         Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
  200.                         // If sign in fails, display a message to the user. If sign in succeeds
  201.                         // the auth state listener will be notified and logic to handle the
  202.                         // signed in user can be handled in the listener.
  203.                         if (!task.isSuccessful()) {
  204.                             Log.w(TAG, "signInWithCredential", task.getException());
  205.                             Toast.makeText(LoginActivity.this, "Authentication failed.",
  206.                                     Toast.LENGTH_SHORT).show();
  207.                         }
  208.                     }
  209.                 });
  210.     }
  211.  
  212.     /**
  213.      * Método que ligo o resultado do Google ao login do Firebase
  214.      * com sucesso, no método de retorno de chamada onSuccess do LoginButton,
  215.      * obtenha um token de acesso para o usuário conectado,
  216.      * troque-o por uma credencial do Firebase e autentique com o Firebase usando essa credencial:
  217.      *
  218.      * @param acct
  219.      */
  220.     private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
  221.         Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
  222.  
  223.         AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
  224.         mAuth.signInWithCredential(credential)
  225.                 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  226.                     @Override
  227.                     public void onComplete(@NonNull Task<AuthResult> task) {
  228.                         Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
  229.                         // If sign in fails, display a message to the user. If sign in succeeds
  230.                         // the auth state listener will be notified and logic to handle the
  231.                         // signed in user can be handled in the listener.
  232.                         if (!task.isSuccessful()) {
  233.                             Log.w(TAG, "signInWithCredential", task.getException());
  234.                             Toast.makeText(LoginActivity.this, "Authentication failed. gg",
  235.                                     Toast.LENGTH_SHORT).show();
  236.                         }
  237.                     }
  238.                 });
  239.     }
  240.  
  241.     /**
  242.      * Call firebase e inicia o listener
  243.      */
  244.     private void firebaseCall() {
  245.  
  246.         mAuthListener = new FirebaseAuth.AuthStateListener() {
  247.             @Override
  248.             public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  249.                 FirebaseUser user = firebaseAuth.getCurrentUser();
  250.                 if (user != null) {
  251.                     // User is signed in
  252.  
  253.                     String name = user.getDisplayName();
  254.                     String email = user.getEmail();
  255.                     Uri photoUrl = user.getPhotoUrl();
  256.  
  257.                     String photo = photoUrl.toString();
  258.  
  259.                     cadastraNoBancoComRedeSocial(name, email, photo);
  260.  
  261.                     Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
  262.                 } else {
  263.                     // User is signed out
  264.                     Log.d(TAG, "onAuthStateChanged:signed_out");
  265.                 }
  266.             }
  267.         };
  268.     }
  269.  
  270.     @Override
  271.     public void onActivityResult(int requestCode, int resultCode, Intent data) {
  272.         super.onActivityResult(requestCode, resultCode, data);
  273.  
  274.         progress.show();
  275.  
  276.         // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
  277.         if (requestCode == RC_SIGN_IN) {
  278.             GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
  279.             String aqui = result.getStatus().getStatusMessage();
  280.             if (result.isSuccess()) {
  281.                 // Google Sign In was successful, authenticate with Firebase
  282.                 GoogleSignInAccount account = result.getSignInAccount();
  283.                 firebaseAuthWithGoogle(account);
  284.             } else {
  285.                 // Google Sign In failed, update UI appropriately
  286.                 int x = 1;
  287.  
  288.             }
  289.         } else {
  290.             //Facebook
  291.             mCallbackManager.onActivityResult(requestCode, resultCode, data);
  292.         }
  293.     }
  294.  
  295.  
  296.     @Override
  297.     public void onStart() {
  298.         super.onStart();
  299.         mAuth.addAuthStateListener(mAuthListener);
  300.     }
  301.  
  302.     @Override
  303.     public void onStop() {
  304.         super.onStop();
  305.         if (mAuthListener != null) {
  306.             mAuth.removeAuthStateListener(mAuthListener);
  307.         }
  308.     }
  309.  
  310.  
  311.     /**
  312.      * Chama os listeners para os botões
  313.      */
  314.     public void listenersButtons() {
  315.  
  316.         entrar.setOnClickListener(new View.OnClickListener() {
  317.             @Override
  318.             public void onClick(View v) {
  319.  
  320.                 if (isNetworkAvailable()) {
  321.                     getDadosUser();
  322.                 } else {
  323.                     Snackbar.make(findViewById(android.R.id.content), getString(R.string.string_internetmsg), Snackbar.LENGTH_SHORT).show();
  324.                 }
  325.  
  326.             }
  327.         });
  328.  
  329.  
  330.         signInButton.setOnClickListener(new View.OnClickListener() {
  331.             @Override
  332.             public void onClick(View v) {
  333.  
  334.                 if (isNetworkAvailable()) {
  335.                     signIn();
  336.                 } else {
  337.                     Snackbar.make(findViewById(android.R.id.content), getString(R.string.string_internetmsg), Snackbar.LENGTH_SHORT).show();
  338.                 }
  339.             }
  340.         });
  341.  
  342.         cadastre_aqui.setOnClickListener(new View.OnClickListener() {
  343.             @Override
  344.             public void onClick(View v) {
  345.                 callDialogCadastro();
  346.             }
  347.         });
  348.     }
  349.  
  350.     private void getDadosUser() {
  351.  
  352.         String e_mail = email.getText().toString();
  353.         String password = senha.getText().toString();
  354.  
  355.         if (e_mail.matches("")) {
  356.             AlertUtils.makeToastShort(getApplicationContext(), "Coloque seu email por favor");
  357.         } else {
  358.             if (password.matches("")) {
  359.                 AlertUtils.makeToastShort(getApplicationContext(), "Coloque uma descrição por favor");
  360.             } else {
  361.                 if (!e_mail.contains("@")||e_mail.length() < 7) {
  362.                     AlertUtils.makeToastShort(getApplicationContext(), "Colque um e-mail válido");
  363.                 } else {
  364.                     if (password.length() < 6) {
  365.                         AlertUtils.makeToastShort(getApplicationContext(), "Senha deve ter 6 dígitos ou mais");
  366.                     } else {
  367.                          fazLoginComum(e_mail, password);
  368.                         progress.show();
  369.                     }
  370.                 }
  371.             }
  372.         }
  373.     }
  374.  
  375.     /**
  376.      * Faz o login comum no sistema.
  377.      * @param email
  378.      * @param password
  379.      */
  380.     private void fazLoginComum(String email, String password) {
  381.  
  382.         //Se o resultado for um status de que o cara está no banco, dai faz login automatico
  383.         mService.loginComum(this, email, password, new GenericListener<User>() {
  384.             @Override
  385.             public void gotGenericSuccess(User response) {
  386.                 setModel(response);
  387.             }
  388.  
  389.             @Override
  390.             public void showErrorMessage(String message) {
  391.                 progress.dismiss();
  392.                 AlertUtils.makeToast(getApplicationContext(), message);
  393.             }
  394.  
  395.             @Override
  396.             public void gotGenericsFailure(String message) {
  397.                 progress.dismiss();
  398.                 AlertUtils.makeToast(getApplicationContext(), message);
  399.             }
  400.         });
  401.     }
  402.  
  403.     /**
  404.      * Chama um dialog para fazer cadastro comum.
  405.      */
  406.     public void callDialogCadastro() {
  407.  
  408.         DialogFragment novoDialogo = new CadastroDialog();
  409.         novoDialogo.show(this.getSupportFragmentManager(), "TAG");
  410.     }
  411.  
  412.  
  413.     /**
  414.      * Acessa o banco e cadastra no servidor os dados do usuário. Infos vindas de rede social.
  415.      *
  416.      * @param name
  417.      * @param email
  418.      * @param photoUrl
  419.      */
  420.     public void cadastraNoBancoComRedeSocial(String name, String email, String photoUrl) {
  421.  
  422.         //Se o resultado for um status de que o cara está no banco, dai faz login automatico
  423.         mService.cadastrarUserRS(this, email, name, photoUrl, new GenericListener<User>() {
  424.             @Override
  425.             public void gotGenericSuccess(User response) {
  426.                 setModel(response);
  427.             }
  428.  
  429.             @Override
  430.             public void showErrorMessage(String message) {
  431.                 progress.dismiss();
  432.                 AlertUtils.makeToast(getApplicationContext(), message);
  433.             }
  434.  
  435.             @Override
  436.             public void gotGenericsFailure(String message) {
  437.                 progress.dismiss();
  438.                 AlertUtils.makeToast(getApplicationContext(), message);
  439.             }
  440.         });
  441.     }
  442.  
  443.     /**
  444.      * Método que seta o model com as infos.
  445.      * @param response
  446.      */
  447.     private void setModel(User response) {
  448.  
  449.         if (response != null && response.getUid() != null) {
  450.             salvaDadosUserLocal(response.getName(), response.getEmail(), response.getUid(), response.getProfile_image());
  451.             iniciaMain();
  452.         } else  //must be error object
  453.         {
  454.             AlertUtils.makeToast(getApplicationContext(), "Erro ao fazer o login. Confira e-mail e senha e tente novamente.");
  455.             progress.dismiss();
  456.         }
  457.     }
  458.  
  459.     /**
  460.      * Método que inicia a main.
  461.      */
  462.     private void iniciaMain() {
  463.         progress.dismiss();
  464.         Intent intent = new Intent(this, MainActivity.class);
  465.         startActivity(intent);
  466.         this.finish();
  467.     }
  468.  
  469.  
  470.  
  471.     /**
  472.      * Salva usuário em sharedPreference.
  473.      *
  474.      * @param nomeUsuario
  475.      * @param emailUsuario
  476.      * @param id_Usuario
  477.      * @param fotoUsuario
  478.      */
  479.     public void salvaDadosUserLocal(String nomeUsuario, String emailUsuario, String id_Usuario, String fotoUsuario) {
  480.         editor.putString("nomeUsuario", nomeUsuario);
  481.         editor.putString("emailUsuario", emailUsuario);
  482.         editor.putString("idUsuario", id_Usuario);
  483.         editor.putString("fotoUsuario", fotoUsuario);
  484.         editor.commit();
  485.     }
  486.  
  487.     /**
  488.      * Verificação se a network está ativa
  489.      *
  490.      * @return
  491.      */
  492.     public boolean isNetworkAvailable() {
  493.  
  494.         ConnectivityManager connectivityManager =
  495.                 (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  496.         NetworkInfo activeNetworkInfo = connectivityManager
  497.                 .getActiveNetworkInfo();
  498.         return activeNetworkInfo != null;
  499.     }
  500.  
  501.  
  502.     @Override
  503.     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  504.         // An unresolvable error has occurred and Google APIs (including Sign-In) will not
  505.         // be available.
  506.         Log.d(TAG, "onConnectionFailed:" + connectionResult);
  507.  
  508.     }
  509. }
Add Comment
Please, Sign In to add comment