Guest User

Untitled

a guest
Oct 24th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.66 KB | None | 0 0
  1. package com.job.darasastudent.ui;
  2.  
  3. import android.content.ActivityNotFoundException;
  4. import android.content.Intent;
  5. import android.graphics.Color;
  6. import android.os.Bundle;
  7. import android.support.annotation.NonNull;
  8. import android.support.design.widget.Snackbar;
  9. import android.support.design.widget.TextInputLayout;
  10. import android.support.v7.app.AppCompatActivity;
  11. import android.util.Log;
  12. import android.view.View;
  13. import android.widget.Button;
  14. import android.widget.LinearLayout;
  15. import android.widget.TextView;
  16.  
  17. import com.google.android.gms.auth.api.signin.GoogleSignIn;
  18. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
  19. import com.google.android.gms.auth.api.signin.GoogleSignInClient;
  20. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
  21. import com.google.android.gms.common.api.ApiException;
  22. import com.google.android.gms.tasks.OnCompleteListener;
  23. import com.google.android.gms.tasks.OnFailureListener;
  24. import com.google.android.gms.tasks.OnSuccessListener;
  25. import com.google.android.gms.tasks.Task;
  26. import com.google.firebase.auth.AuthCredential;
  27. import com.google.firebase.auth.AuthResult;
  28. import com.google.firebase.auth.FirebaseAuth;
  29. import com.google.firebase.auth.FirebaseUser;
  30. import com.google.firebase.auth.GoogleAuthProvider;
  31. import com.google.firebase.firestore.DocumentReference;
  32. import com.google.firebase.firestore.DocumentSnapshot;
  33. import com.google.firebase.firestore.FirebaseFirestore;
  34. import com.google.firebase.iid.FirebaseInstanceId;
  35. import com.job.darasastudent.R;
  36. import com.job.darasastudent.model.StudentDetails;
  37. import com.job.darasastudent.util.AppStatus;
  38. import com.job.darasastudent.util.DoSnack;
  39.  
  40. import butterknife.BindView;
  41. import butterknife.ButterKnife;
  42. import butterknife.OnClick;
  43. import cn.pedant.SweetAlert.SweetAlertDialog;
  44.  
  45. import static com.job.darasastudent.util.Constants.STUDENTDETAILSCOL;
  46.  
  47. public class LoginActivity extends AppCompatActivity {
  48.  
  49. @BindView(R.id.login_email)
  50. TextInputLayout loginEmail;
  51. @BindView(R.id.login_password)
  52. TextInputLayout loginPassword;
  53. @BindView(R.id.forgotpass)
  54. TextView forgotpass;
  55. @BindView(R.id.login_button)
  56. Button loginButton;
  57. @BindView(R.id.login_via_google)
  58. LinearLayout loginViaGoogle;
  59.  
  60. private static final String TAG = "login";
  61. public static final int RC_SIGN_IN = 1001;
  62.  
  63.  
  64. private FirebaseAuth mAuth;
  65. private FirebaseFirestore mFirestore;
  66.  
  67. private DoSnack doSnack;
  68. private GoogleSignInClient mGoogleSignInClient;
  69.  
  70. @Override
  71. protected void onCreate(Bundle savedInstanceState) {
  72. super.onCreate(savedInstanceState);
  73. setContentView(R.layout.login_xml);
  74. ButterKnife.bind(this);
  75.  
  76. //firebase
  77. mAuth = FirebaseAuth.getInstance();
  78. mFirestore = FirebaseFirestore.getInstance();
  79.  
  80. // Configure Google Sign In
  81. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  82. .requestIdToken(getString(R.string.default_web_client_id))
  83. .requestEmail()
  84. .build();
  85.  
  86. // Build a GoogleSignInClient with the options specified by gso.
  87. mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
  88.  
  89. doSnack = new DoSnack(this, LoginActivity.this);
  90. }
  91.  
  92. @Override
  93. protected void onStart() {
  94. super.onStart();
  95.  
  96. if (FirebaseAuth.getInstance().getCurrentUser() != null) {
  97. sendToMain();
  98. }
  99. }
  100.  
  101. @OnClick(R.id.forgotpass)
  102. public void onForgotpassClicked() {
  103.  
  104. final String email = loginEmail.getEditText().getText().toString();
  105.  
  106.  
  107. if (email.isEmpty() || !isEmailValid(email)) {
  108. loginEmail.setError("enter valid email to reset password");
  109. return;
  110. } else {
  111. loginEmail.setError(null);
  112. }
  113.  
  114. mAuth.sendPasswordResetEmail(email)
  115. .addOnCompleteListener(new OnCompleteListener<Void>() {
  116. @Override
  117. public void onComplete(@NonNull Task<Void> task) {
  118. if (task.isSuccessful()) {
  119. Log.d(TAG, "Email sent.");
  120. doSnack.showSnackbar("Email sent to " + email, "Check", new View.OnClickListener() {
  121. @Override
  122. public void onClick(View view) {
  123.  
  124. Intent intent = new Intent(Intent.ACTION_MAIN);
  125. intent.addCategory(Intent.CATEGORY_APP_EMAIL);
  126. try {
  127. //startActivity(intent);
  128. startActivity(Intent.createChooser(intent, getString(R.string.chooseEmailClient)));
  129. } catch (ActivityNotFoundException e) { }
  130. }
  131. });
  132. }else {
  133. doSnack.showShortSnackbar("You're not registered :(");
  134. }
  135. }
  136. });
  137. }
  138.  
  139. @OnClick(R.id.login_button)
  140. public void onLoginButtonClicked() {
  141.  
  142. if (!AppStatus.getInstance(getApplicationContext()).isOnline()) {
  143.  
  144. doSnack.showSnackbar("You're offline", "Retry", new View.OnClickListener() {
  145. @Override
  146. public void onClick(View view) {
  147. onLoginButtonClicked();
  148. }
  149. });
  150.  
  151. return;
  152. }
  153.  
  154.  
  155. String email = loginEmail.getEditText().getText().toString();
  156. String password = loginPassword.getEditText().getText().toString();
  157.  
  158. if (validate()) {
  159.  
  160. final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
  161. pDialog.getProgressHelper().setBarColor(Color.parseColor("#FF5521"));
  162. pDialog.setTitleText("Logging in...");
  163. pDialog.setCancelable(false);
  164. pDialog.show();
  165.  
  166. mAuth.signInWithEmailAndPassword(email, password)
  167. .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
  168. @Override
  169. public void onComplete(@NonNull Task<AuthResult> authtask) {
  170. if (authtask.isSuccessful()) {
  171.  
  172. //login successful
  173.  
  174. //update device token
  175.  
  176. String devicetoken = FirebaseInstanceId.getInstance().getToken();
  177. String mCurrentUserid = FirebaseAuth.getInstance().getCurrentUser().getUid();
  178.  
  179. // Set the value of 'Users'
  180. DocumentReference usersRef = mFirestore.collection(STUDENTDETAILSCOL).document(mCurrentUserid);
  181.  
  182. usersRef.update("devicetoken", devicetoken)
  183. .addOnSuccessListener(new OnSuccessListener<Void>() {
  184. @Override
  185. public void onSuccess(Void aVoid) {
  186. pDialog.dismissWithAnimation();
  187. sendToMain();
  188. }
  189. }).addOnFailureListener(new OnFailureListener() {
  190. @Override
  191. public void onFailure(@NonNull Exception e) {
  192. pDialog.dismiss();
  193. doSnack.errorPrompt("Oops...", e.getMessage());
  194. }
  195. });
  196.  
  197.  
  198. } else {
  199. pDialog.dismiss();
  200. doSnack.UserAuthToastExceptions(authtask);
  201. }
  202. }
  203. });
  204. }
  205.  
  206. }
  207.  
  208. @OnClick({R.id.login_via_google, R.id.login_via_google_image})
  209. public void onLoginViaGoogleClicked() {
  210.  
  211. if (!AppStatus.getInstance(getApplicationContext()).isOnline()) {
  212.  
  213. doSnack.showSnackbar("You're offline", "Retry", new View.OnClickListener() {
  214. @Override
  215. public void onClick(View view) {
  216. onLoginViaGoogleClicked();
  217. }
  218. });
  219.  
  220. return;
  221. }
  222.  
  223. Intent signInIntent = mGoogleSignInClient.getSignInIntent();
  224. startActivityForResult(signInIntent, RC_SIGN_IN);
  225. loginViaGoogle.setEnabled(false);
  226. }
  227.  
  228. private void sendToMain() {
  229.  
  230. Intent mainIntent = new Intent(this, MainActivity.class);
  231. mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  232. mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  233. startActivity(mainIntent);
  234. finish();
  235. }
  236.  
  237. private boolean validate() {
  238. boolean valid = true;
  239.  
  240. String email = loginEmail.getEditText().getText().toString();
  241. String password = loginPassword.getEditText().getText().toString();
  242.  
  243. if (email.isEmpty() || !isEmailValid(email)) {
  244. loginEmail.setError("enter valid email");
  245. valid = false;
  246. } else {
  247. loginEmail.setError(null);
  248. }
  249.  
  250. if (password.isEmpty() || password.length() < 6) {
  251. loginPassword.setError("at least 6 characters");
  252. valid = false;
  253. } else {
  254. loginPassword.setError(null);
  255. }
  256.  
  257. return valid;
  258. }
  259.  
  260. private boolean isEmailValid(CharSequence email) {
  261. return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
  262. }
  263.  
  264. @Override
  265. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  266. super.onActivityResult(requestCode, resultCode, data);
  267.  
  268. //Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
  269.  
  270. if (requestCode == RC_SIGN_IN) {
  271. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
  272. try {
  273. // Google Sign In was successful, authenticate with Firebase
  274. GoogleSignInAccount account = task.getResult(ApiException.class);
  275. firebaseAuthWithGoogle(account);
  276. } catch (ApiException e) {
  277. // Google Sign In failed, update UI appropriately
  278. Log.w(TAG, "Google sign in failed", e);
  279. // ...
  280. Snackbar.make(findViewById(android.R.id.content), "Google sign in failed", Snackbar.LENGTH_LONG).show();
  281. loginViaGoogle.setEnabled(true);
  282. }
  283. }
  284. }
  285.  
  286. private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
  287. Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
  288.  
  289. final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
  290. pDialog.getProgressHelper().setBarColor(Color.parseColor("#FF5521"));
  291. pDialog.setTitleText("Logging in...");
  292. pDialog.setCancelable(false);
  293. pDialog.show();
  294.  
  295. AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
  296. mAuth.signInWithCredential(credential)
  297. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  298. @Override
  299. public void onComplete(@NonNull Task<AuthResult> task) {
  300. if (task.isSuccessful()) {
  301. // Sign in success, update UI with the signed-in user's information
  302. Log.d(TAG, "signInWithCredential:success");
  303. final FirebaseUser user = mAuth.getCurrentUser();
  304.  
  305. final String device_token = FirebaseInstanceId.getInstance().getToken();
  306. final String mCurrentUserid = mAuth.getCurrentUser().getUid();
  307.  
  308. // refactor this not to write to DB each time...check if account exists
  309.  
  310. DocumentReference docReference = mFirestore.collection(STUDENTDETAILSCOL).document(mCurrentUserid);
  311. docReference.get()
  312. .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
  313. @Override
  314. public void onComplete(@NonNull Task<DocumentSnapshot> task) {
  315. if (task.isSuccessful()) {
  316. DocumentSnapshot document = task.getResult();
  317. if (document.exists()) {
  318. Log.d(TAG, "DocumentSnapshot data: " + document.getData());
  319.  
  320. //update token only
  321. updateTokenOnly(mCurrentUserid, device_token, pDialog);
  322.  
  323. } else {
  324. Log.d(TAG, "No such document");
  325.  
  326. //logging in with no pre account
  327. //region create fresh account
  328.  
  329. pDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
  330. pDialog.setTitleText("Account doesn't exists! \n Creating one...");
  331.  
  332. //write to db
  333. writingToStudUsers(pDialog, device_token, user, mCurrentUserid);
  334.  
  335. //endregion
  336. }
  337. } else {
  338. Log.d(TAG, "get failed with ", task.getException());
  339. }
  340. }
  341. });
  342. } else {
  343. // If sign in fails, display a message to the user.
  344. pDialog.dismissWithAnimation();
  345. Log.w(TAG, "signInWithCredential:failure", task.getException());
  346. Snackbar.make(findViewById(android.R.id.content), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
  347. loginViaGoogle.setEnabled(true);
  348. }
  349. }
  350. });
  351. }
  352.  
  353. private void writingToStudUsers(final SweetAlertDialog pDialog, String device_token, FirebaseUser user, String mCurrentUserid) {
  354.  
  355. StudentDetails studentDetails = new StudentDetails();
  356. studentDetails.setDevicetoken(device_token);
  357. studentDetails.setPhotourl(user.getPhotoUrl().toString());
  358. studentDetails.setFirstname(user.getDisplayName());
  359. studentDetails.setStudentid(mCurrentUserid);
  360.  
  361. // Set the value of 'Users'
  362. DocumentReference usersRef = mFirestore.collection(STUDENTDETAILSCOL).document(mCurrentUserid);
  363.  
  364. usersRef.set(studentDetails)
  365. .addOnSuccessListener(new OnSuccessListener<Void>() {
  366. @Override
  367. public void onSuccess(Void aVoid) {
  368. pDialog.dismissWithAnimation();
  369. sendToAccountSetup();
  370.  
  371. }
  372. }).addOnFailureListener(new OnFailureListener() {
  373. @Override
  374. public void onFailure(@NonNull Exception e) {
  375. pDialog.dismiss();
  376. doSnack.errorPrompt("Oops...", e.getMessage());
  377. }
  378. });
  379. }
  380.  
  381. private void updateTokenOnly(String mCurrentUserid, String device_token, final SweetAlertDialog pDialog) {
  382. //update device token
  383.  
  384. // Set the value of 'Users'
  385. DocumentReference usersRef = mFirestore.collection(STUDENTDETAILSCOL).document(mCurrentUserid);
  386.  
  387. usersRef.update("devicetoken", device_token)
  388. .addOnSuccessListener(new OnSuccessListener<Void>() {
  389. @Override
  390. public void onSuccess(Void aVoid) {
  391. pDialog.dismissWithAnimation();
  392. sendToMain();
  393. }
  394. }).addOnFailureListener(new OnFailureListener() {
  395. @Override
  396. public void onFailure(@NonNull Exception e) {
  397. pDialog.dismiss();
  398. doSnack.errorPrompt("Oops...", e.getMessage());
  399. }
  400. });
  401.  
  402. }
  403.  
  404. private void sendToAccountSetup() {
  405. Intent aIntent = new Intent(this, AccountSetupActivity.class);
  406. aIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  407. aIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  408. startActivity(aIntent);
  409. finish();
  410. }
  411. }
Add Comment
Please, Sign In to add comment