PageRenderTime 91ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/app/src/main/java/com/wasim/ksapp/ui/LoginActivity.java

https://bitbucket.org/WasimShahul/ksapp
Java | 368 lines | 302 code | 28 blank | 38 comment | 22 complexity | 8d4a1731c129b9d7a9e0ee532d6abd02 MD5 | raw file
  1. package com.wasim.ksapp.ui;
  2. import android.app.ActivityOptions;
  3. import android.content.Intent;
  4. import android.os.Build;
  5. import android.os.Bundle;
  6. import android.support.annotation.NonNull;
  7. import android.support.design.widget.FloatingActionButton;
  8. import android.support.v7.app.AppCompatActivity;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.widget.EditText;
  12. import android.widget.Toast;
  13. import com.google.android.gms.tasks.OnCompleteListener;
  14. import com.google.android.gms.tasks.OnFailureListener;
  15. import com.google.android.gms.tasks.Task;
  16. import com.google.firebase.auth.AuthResult;
  17. import com.google.firebase.auth.FirebaseAuth;
  18. import com.google.firebase.auth.FirebaseUser;
  19. import com.google.firebase.database.DataSnapshot;
  20. import com.google.firebase.database.DatabaseError;
  21. import com.google.firebase.database.FirebaseDatabase;
  22. import com.google.firebase.database.ValueEventListener;
  23. import com.wasim.ksapp.MainActivity;
  24. import com.wasim.ksapp.R;
  25. import com.wasim.ksapp.data.SharedPreferenceHelper;
  26. import com.wasim.ksapp.data.StaticConfig;
  27. import com.wasim.ksapp.model.User;
  28. import com.yarolegovich.lovelydialog.LovelyInfoDialog;
  29. import com.yarolegovich.lovelydialog.LovelyProgressDialog;
  30. import java.util.HashMap;
  31. import java.util.regex.Matcher;
  32. import java.util.regex.Pattern;
  33. public class LoginActivity extends AppCompatActivity {
  34. private static String TAG = "LoginActivity";
  35. FloatingActionButton fab;
  36. private final Pattern VALID_EMAIL_ADDRESS_REGEX =
  37. Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
  38. private EditText editTextUsername, editTextPassword;
  39. private LovelyProgressDialog waitingDialog;
  40. private AuthUtils authUtils;
  41. private FirebaseAuth mAuth;
  42. private FirebaseAuth.AuthStateListener mAuthListener;
  43. private FirebaseUser user;
  44. private boolean firstTimeAccess;
  45. @Override
  46. protected void onStart() {
  47. super.onStart();
  48. mAuth.addAuthStateListener(mAuthListener);
  49. }
  50. @Override
  51. protected void onCreate(Bundle savedInstanceState) {
  52. super.onCreate(savedInstanceState);
  53. setContentView(R.layout.activity_login);
  54. fab = (FloatingActionButton) findViewById(R.id.fab);
  55. editTextUsername = (EditText) findViewById(R.id.et_username);
  56. editTextPassword = (EditText) findViewById(R.id.et_password);
  57. firstTimeAccess = true;
  58. initFirebase();
  59. }
  60. /**
  61. * Khởi tạo các thành phần cần thiết cho việc quản lý đăng nhập
  62. */
  63. private void initFirebase() {
  64. //Khoi tao thanh phan de dang nhap, dang ky
  65. mAuth = FirebaseAuth.getInstance();
  66. authUtils = new AuthUtils();
  67. mAuthListener = new FirebaseAuth.AuthStateListener() {
  68. @Override
  69. public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  70. user = firebaseAuth.getCurrentUser();
  71. if (user != null) {
  72. // User is signed in
  73. StaticConfig.UID = user.getUid();
  74. Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
  75. if (firstTimeAccess) {
  76. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  77. LoginActivity.this.finish();
  78. }
  79. } else {
  80. Log.d(TAG, "onAuthStateChanged:signed_out");
  81. }
  82. firstTimeAccess = false;
  83. }
  84. };
  85. //Khoi tao dialog waiting khi dang nhap
  86. waitingDialog = new LovelyProgressDialog(this).setCancelable(false);
  87. }
  88. @Override
  89. protected void onStop() {
  90. super.onStop();
  91. if (mAuthListener != null) {
  92. mAuth.removeAuthStateListener(mAuthListener);
  93. }
  94. }
  95. public void clickRegisterLayout(View view) {
  96. getWindow().setExitTransition(null);
  97. getWindow().setEnterTransition(null);
  98. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  99. ActivityOptions options =
  100. ActivityOptions.makeSceneTransitionAnimation(this, fab, fab.getTransitionName());
  101. startActivityForResult(new Intent(this, RegisterActivity.class), StaticConfig.REQUEST_CODE_REGISTER, options.toBundle());
  102. } else {
  103. startActivityForResult(new Intent(this, RegisterActivity.class), StaticConfig.REQUEST_CODE_REGISTER);
  104. }
  105. }
  106. @Override
  107. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  108. super.onActivityResult(requestCode, resultCode, data);
  109. if (requestCode == StaticConfig.REQUEST_CODE_REGISTER && resultCode == RESULT_OK) {
  110. authUtils.createUser(data.getStringExtra(StaticConfig.STR_EXTRA_USERNAME), data.getStringExtra(StaticConfig.STR_EXTRA_PASSWORD));
  111. }
  112. }
  113. public void clickLogin(View view) {
  114. String username = editTextUsername.getText().toString();
  115. String password = editTextPassword.getText().toString();
  116. if (validate(username, password)) {
  117. authUtils.signIn(username, password);
  118. } else {
  119. Toast.makeText(this, "Invalid email or empty password", Toast.LENGTH_SHORT).show();
  120. }
  121. }
  122. @Override
  123. public void onBackPressed() {
  124. super.onBackPressed();
  125. setResult(RESULT_CANCELED, null);
  126. finish();
  127. }
  128. private boolean validate(String emailStr, String password) {
  129. Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
  130. return (password.length() > 0 || password.equals(";")) && matcher.find();
  131. }
  132. public void clickResetPassword(View view) {
  133. String username = editTextUsername.getText().toString();
  134. if (validate(username, ";")) {
  135. authUtils.resetPassword(username);
  136. } else {
  137. Toast.makeText(this, "Invalid email", Toast.LENGTH_SHORT).show();
  138. }
  139. }
  140. /**
  141. * Dinh nghia cac ham tien ich cho quas trinhf dang nhap, dang ky,...
  142. */
  143. class AuthUtils {
  144. /**
  145. * Action register
  146. *
  147. * @param email
  148. * @param password
  149. */
  150. void createUser(String email, String password) {
  151. waitingDialog.setIcon(R.drawable.ic_add_friend)
  152. .setTitle("Registering....")
  153. .setTopColorRes(R.color.colorPrimary)
  154. .show();
  155. mAuth.createUserWithEmailAndPassword(email, password)
  156. .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
  157. @Override
  158. public void onComplete(@NonNull Task<AuthResult> task) {
  159. Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
  160. waitingDialog.dismiss();
  161. // If sign in fails, display a message to the user. If sign in succeeds
  162. // the auth state listener will be notified and logic to handle the
  163. // signed in user can be handled in the listener.
  164. if (!task.isSuccessful()) {
  165. new LovelyInfoDialog(LoginActivity.this) {
  166. @Override
  167. public LovelyInfoDialog setConfirmButtonText(String text) {
  168. findView(com.yarolegovich.lovelydialog.R.id.ld_btn_confirm).setOnClickListener(new View.OnClickListener() {
  169. @Override
  170. public void onClick(View view) {
  171. dismiss();
  172. }
  173. });
  174. return super.setConfirmButtonText(text);
  175. }
  176. }
  177. .setTopColorRes(R.color.colorAccent)
  178. .setIcon(R.drawable.ic_add_friend)
  179. .setTitle("Register false")
  180. .setMessage("Email exist or weak password!")
  181. .setConfirmButtonText("ok")
  182. .setCancelable(false)
  183. .show();
  184. } else {
  185. initNewUserInfo();
  186. Toast.makeText(LoginActivity.this, "Register and Login success", Toast.LENGTH_SHORT).show();
  187. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  188. LoginActivity.this.finish();
  189. }
  190. }
  191. })
  192. .addOnFailureListener(new OnFailureListener() {
  193. @Override
  194. public void onFailure(@NonNull Exception e) {
  195. waitingDialog.dismiss();
  196. }
  197. })
  198. ;
  199. }
  200. /**
  201. * Action Login
  202. *
  203. * @param email
  204. * @param password
  205. */
  206. void signIn(String email, String password) {
  207. waitingDialog.setIcon(R.drawable.ic_person_low)
  208. .setTitle("Login....")
  209. .setTopColorRes(R.color.colorPrimary)
  210. .show();
  211. mAuth.signInWithEmailAndPassword(email, password)
  212. .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
  213. @Override
  214. public void onComplete(@NonNull Task<AuthResult> task) {
  215. Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
  216. // If sign in fails, display a message to the user. If sign in succeeds
  217. // the auth state listener will be notified and logic to handle the
  218. // signed in user can be handled in the listener.
  219. waitingDialog.dismiss();
  220. if (!task.isSuccessful()) {
  221. Log.w(TAG, "signInWithEmail:failed", task.getException());
  222. new LovelyInfoDialog(LoginActivity.this) {
  223. @Override
  224. public LovelyInfoDialog setConfirmButtonText(String text) {
  225. findView(com.yarolegovich.lovelydialog.R.id.ld_btn_confirm).setOnClickListener(new View.OnClickListener() {
  226. @Override
  227. public void onClick(View view) {
  228. dismiss();
  229. }
  230. });
  231. return super.setConfirmButtonText(text);
  232. }
  233. }
  234. .setTopColorRes(R.color.colorAccent)
  235. .setIcon(R.drawable.ic_person_low)
  236. .setTitle("Login false")
  237. .setMessage("Email not exist or wrong password!")
  238. .setCancelable(false)
  239. .setConfirmButtonText("Ok")
  240. .show();
  241. } else {
  242. saveUserInfo();
  243. startActivity(new Intent(LoginActivity.this, MainActivity.class));
  244. LoginActivity.this.finish();
  245. }
  246. }
  247. })
  248. .addOnFailureListener(new OnFailureListener() {
  249. @Override
  250. public void onFailure(@NonNull Exception e) {
  251. waitingDialog.dismiss();
  252. }
  253. });
  254. }
  255. /**
  256. * Action reset password
  257. *
  258. * @param email
  259. */
  260. void resetPassword(final String email) {
  261. mAuth.sendPasswordResetEmail(email)
  262. .addOnCompleteListener(new OnCompleteListener<Void>() {
  263. @Override
  264. public void onComplete(@NonNull Task<Void> task) {
  265. new LovelyInfoDialog(LoginActivity.this) {
  266. @Override
  267. public LovelyInfoDialog setConfirmButtonText(String text) {
  268. findView(com.yarolegovich.lovelydialog.R.id.ld_btn_confirm).setOnClickListener(new View.OnClickListener() {
  269. @Override
  270. public void onClick(View view) {
  271. dismiss();
  272. }
  273. });
  274. return super.setConfirmButtonText(text);
  275. }
  276. }
  277. .setTopColorRes(R.color.colorPrimary)
  278. .setIcon(R.drawable.ic_pass_reset)
  279. .setTitle("Password Recovery")
  280. .setMessage("Sent email to " + email)
  281. .setConfirmButtonText("Ok")
  282. .show();
  283. }
  284. })
  285. .addOnFailureListener(new OnFailureListener() {
  286. @Override
  287. public void onFailure(@NonNull Exception e) {
  288. new LovelyInfoDialog(LoginActivity.this) {
  289. @Override
  290. public LovelyInfoDialog setConfirmButtonText(String text) {
  291. findView(com.yarolegovich.lovelydialog.R.id.ld_btn_confirm).setOnClickListener(new View.OnClickListener() {
  292. @Override
  293. public void onClick(View view) {
  294. dismiss();
  295. }
  296. });
  297. return super.setConfirmButtonText(text);
  298. }
  299. }
  300. .setTopColorRes(R.color.colorAccent)
  301. .setIcon(R.drawable.ic_pass_reset)
  302. .setTitle("False")
  303. .setMessage("False to sent email to " + email)
  304. .setConfirmButtonText("Ok")
  305. .show();
  306. }
  307. });
  308. }
  309. /**
  310. * Luu thong tin user info cho nguoi dung dang nhap
  311. */
  312. void saveUserInfo() {
  313. FirebaseDatabase.getInstance().getReference().child("user/" + StaticConfig.UID).addListenerForSingleValueEvent(new ValueEventListener() {
  314. @Override
  315. public void onDataChange(DataSnapshot dataSnapshot) {
  316. waitingDialog.dismiss();
  317. HashMap hashUser = (HashMap) dataSnapshot.getValue();
  318. User userInfo = new User();
  319. userInfo.name = (String) hashUser.get("name");
  320. userInfo.email = (String) hashUser.get("email");
  321. userInfo.avata = (String) hashUser.get("avata");
  322. SharedPreferenceHelper.getInstance(LoginActivity.this).saveUserInfo(userInfo);
  323. }
  324. @Override
  325. public void onCancelled(DatabaseError databaseError) {
  326. }
  327. });
  328. }
  329. /**
  330. * Khoi tao thong tin mac dinh cho tai khoan moi
  331. */
  332. void initNewUserInfo() {
  333. User newUser = new User();
  334. newUser.email = user.getEmail();
  335. newUser.name = user.getEmail().substring(0, user.getEmail().indexOf("@"));
  336. newUser.avata = StaticConfig.STR_DEFAULT_BASE64;
  337. FirebaseDatabase.getInstance().getReference().child("user/" + user.getUid()).setValue(newUser);
  338. }
  339. }
  340. }