Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.50 KB | None | 0 0
  1. public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener{
  2.  
  3. private EditText emailEditText;
  4. private EditText passwordEditText;
  5.  
  6. private FirebaseAuth mFirebaseAuth;
  7. private FirebaseAuth.AuthStateListener mAuthStateListener;
  8. private RelativeLayout progressBar;
  9.  
  10. private GoogleApiClient mGoogleApiClient;
  11. private volatile boolean googleSignOn;
  12. private long lastClickTime = 0;
  13.  
  14. private static final int RC_SIGN_IN = 9001;
  15.  
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_login);
  20. if(FirebaseAuth.getInstance().getCurrentUser() != null){
  21. progressBar = (RelativeLayout) findViewById(R.id.loginProgressBar);
  22. progressBar.setVisibility(View.VISIBLE);
  23. progressBar.bringToFront();
  24. setupUsersManager();
  25. }
  26. Calligrapher calligrapher = new Calligrapher(this);
  27. calligrapher.setFont(this, "fonts/GothamRoundedMedium_21022.ttf", true);
  28.  
  29. emailEditText = (EditText) findViewById(R.id.email);
  30. passwordEditText = (EditText) findViewById(R.id.password);
  31.  
  32. mFirebaseAuth = FirebaseAuth.getInstance();
  33. googleSignOn = new Boolean(false);
  34.  
  35. // Configure sign-in to request the user's ID, email address, and basic
  36. // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
  37. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  38. .requestIdToken(getString(R.string.default_web_client))
  39. .requestEmail()
  40. .build();
  41.  
  42.  
  43. // Build a GoogleApiClient with access to the Google Sign-In API and the
  44. // options specified by gso.
  45. mGoogleApiClient = new GoogleApiClient.Builder(this)
  46. .enableAutoManage(this /* Activity */, this /* OnConnectionFailedListener */)
  47. .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
  48. .build();
  49.  
  50. //set clicklistener for signup button
  51. findViewById(R.id.signUpButton).setOnClickListener(this);
  52. findViewById(R.id.signInButton).setOnClickListener(this);
  53. findViewById(R.id.googleSignIn).setOnClickListener(this);
  54.  
  55. mAuthStateListener = new FirebaseAuth.AuthStateListener() {
  56. @Override
  57. public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  58. FirebaseUser user = mFirebaseAuth.getCurrentUser();
  59.  
  60. if(user != null) {
  61. Log.d("Sign in", user.getDisplayName() + " is signed in");
  62. }
  63. else {
  64. Log.d("Sign in", "user is signed out");
  65. }
  66. }
  67. };
  68. }
  69.  
  70. private void signInWithEmail() {
  71. String email = emailEditText.getText().toString().trim();
  72. String password = passwordEditText.getText().toString().trim();
  73.  
  74. if(TextUtils.isEmpty(email)){
  75. Toast.makeText(LoginActivity.this, "Please be sure to enter email", Toast.LENGTH_SHORT).show();
  76. return;
  77. }
  78. if(TextUtils.isEmpty(password)){
  79. Toast.makeText(LoginActivity.this, "Please be sure to enter password", Toast.LENGTH_SHORT).show();
  80. return;
  81. }
  82.  
  83. mFirebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  84. @Override
  85. public void onComplete(@NonNull Task<AuthResult> task) {
  86. if(task.isSuccessful()) {
  87. progressBar = (RelativeLayout) findViewById(R.id.loginProgressBar);
  88. progressBar.setVisibility(View.VISIBLE);
  89. progressBar.bringToFront();
  90. setupUsersManager();
  91. }
  92. else {
  93. Toast.makeText(LoginActivity.this, "Something happened!", Toast.LENGTH_SHORT).show();
  94. }
  95. }
  96. });
  97. }
  98.  
  99. @Override
  100. public void onClick(View v) {
  101. //get id of calling element who just clicked
  102. int i = v.getId();
  103. //if clicked signup button
  104. if (i == R.id.signUpButton) {
  105. startActivity(new Intent(LoginActivity.this, SignupActivity.class));
  106. }
  107. else if (i == R.id.signInButton) {
  108. signInWithEmail();
  109. }
  110. else if(i == R.id.googleSignIn) {
  111. findViewById(R.id.googleSignIn).setOnClickListener(null);
  112. signInWithGoogle();
  113. }
  114. }
  115.  
  116. private void signInWithGoogle() {
  117. Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
  118. startActivityForResult(signInIntent, RC_SIGN_IN);
  119. }
  120.  
  121. @Override
  122. public void onStart() {
  123. super.onStart();
  124. mFirebaseAuth.addAuthStateListener(mAuthStateListener);
  125. }
  126.  
  127. @Override
  128. public void onStop() {
  129. super.onStop();
  130. if (mAuthStateListener != null) {
  131. mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
  132. }
  133. }
  134.  
  135.  
  136. private void handleSignInResult(GoogleSignInResult result) {
  137. Log.d("Google Login", "handleSignInResult:" + result.isSuccess());
  138. if (result.isSuccess()) {
  139. progressBar = (RelativeLayout) findViewById(R.id.loginProgressBar);
  140. progressBar.setVisibility(View.VISIBLE);
  141. progressBar.bringToFront();
  142.  
  143. // Signed in successfully, show authenticated UI.
  144. GoogleSignInAccount acct = result.getSignInAccount();
  145. Toast.makeText(LoginActivity.this, "Was successful", Toast.LENGTH_SHORT).show();
  146. firebaseAuthWithGoogle(acct);
  147.  
  148. } else {
  149. // Signed out, show unauthenticated UI.
  150. findViewById(R.id.googleSignIn).setOnClickListener(this);
  151. Toast.makeText(LoginActivity.this, "Was not successful", Toast.LENGTH_SHORT).show();
  152. }
  153. }
  154.  
  155.  
  156. @Override
  157. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  158. super.onActivityResult(requestCode, resultCode, data);
  159. // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
  160. if (requestCode == RC_SIGN_IN) {
  161. GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
  162. handleSignInResult(result);
  163. } else {
  164. findViewById(R.id.googleSignIn).setOnClickListener(this);
  165. }
  166. }
  167.  
  168. @Override
  169. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  170.  
  171. }
  172. @Override
  173. public void onBackPressed() {}
  174.  
  175. private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
  176. Log.d("Auth G w/ F", "firebaseAuthWithGoogle:" + acct.getId());
  177.  
  178. AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
  179. mFirebaseAuth.signInWithCredential(credential)
  180. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  181. @Override
  182. public void onComplete(@NonNull Task<AuthResult> task) {
  183. Log.d("Auth G w/ F", "signInWithCredential:onComplete:" + task.isSuccessful());
  184.  
  185. // If sign in fails, display a message to the user. If sign in succeeds
  186. // the auth state listener will be notified and logic to handle the
  187. // signed in user can be handled in the listener.
  188. if (!task.isSuccessful()) {
  189. Log.w("Auth G w/ F", "signInWithCredential", task.getException());
  190. Toast.makeText(LoginActivity.this, "Authentication failed.",
  191. Toast.LENGTH_SHORT).show();
  192. } else {
  193. setupUsersManager();
  194. }
  195. }
  196. });
  197. }
  198. private void setupUsersManager(){
  199. final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
  200.  
  201. final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
  202.  
  203. if (uid != null){
  204. DatabaseReference ref = mDatabase.child("users");
  205. ref.child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
  206. @Override
  207. public void onDataChange(DataSnapshot dataSnapshot) {
  208. AuthenticatedUser user;
  209. user = dataSnapshot.getValue(AuthenticatedUser.class);
  210.  
  211. if (user == null){
  212. addUserToDatabase();
  213. } else {
  214. AuthenticatedUserManager.getInstance().setUser(user);
  215. getStripeInformation();
  216. startActivity(new Intent(LoginActivity.this, CheckInActivity.class));
  217. finish();
  218. }
  219. }
  220.  
  221. @Override
  222. public void onCancelled(DatabaseError databaseError) {
  223. Log.d("DatabaseCancelled", "Database returned canceled" + databaseError.toString());
  224. }
  225. });
  226. }
  227. }
  228.  
  229. private void getStripeInformation(){
  230. final AuthenticatedUserManager userManager = AuthenticatedUserManager.getInstance();
  231. AuthenticatedUser user = userManager.getUser();
  232.  
  233. if(!TextUtils.isEmpty(user.getStripeCustId()) && user.getStripeCustId()!= null){
  234. // Instantiate the RequestQueue.
  235. RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
  236. String url = "https://sleepy-forest-31423.herokuapp.com/charges/getCustomerPaymentInfo?"
  237. + "stripeCustId=" + user.getStripeCustId();
  238.  
  239. Log.d("URL", url);
  240.  
  241. // Request a string response from the provided URL.
  242. StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
  243. new Response.Listener<String>() {
  244. @Override
  245. public void onResponse(String responseJSON) {
  246. // your response
  247. Log.d("HTTP-RESPONSE", responseJSON);
  248.  
  249. try {
  250. JSONObject obj = new JSONObject(responseJSON);
  251. JSONArray stripeCards = obj.getJSONObject("sources").getJSONArray("data");
  252. String card = stripeCards.getJSONObject(0).getString("brand")
  253. + " " + stripeCards.getJSONObject(0).getString("last4");
  254.  
  255. AuthenticatedUser user = AuthenticatedUserManager.getInstance().getUser();
  256. user.setPayment(card);
  257. user.setStripeCustId(obj.get("id").toString());
  258. user.setStripeInfo(obj);
  259. AuthenticatedUserManager.getInstance().setUser(user);
  260.  
  261. } catch (Throwable t) {
  262. Log.e("FROM OBJ", "Could not parse malformed JSON: "" + responseJSON + """);
  263. }
  264.  
  265. }
  266. }, new Response.ErrorListener() {
  267. @Override
  268. public void onErrorResponse(VolleyError error) {
  269. // error
  270. }
  271. }
  272. );
  273. // Add the request to the RequestQueue.
  274. queue.add(stringRequest);
  275. }
  276. }
  277. private void addUserToDatabase(){
  278. DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
  279. AuthenticatedUser user = new AuthenticatedUser(
  280. mFirebaseAuth.getCurrentUser().getDisplayName(),
  281. "none",
  282. mFirebaseAuth.getCurrentUser().getEmail(),
  283. "none",
  284. "none",
  285. "none"
  286. );
  287. mDatabase.child("users").child(mFirebaseAuth.getCurrentUser().getUid()).setValue(user);
  288.  
  289. mDatabase.child("users").child(mFirebaseAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
  290. @Override
  291. public void onDataChange(DataSnapshot dataSnapshot) {
  292. AuthenticatedUser user;
  293. user = dataSnapshot.getValue(AuthenticatedUser.class);
  294. AuthenticatedUserManager.getInstance().setUser(user);
  295. getStripeInformation();
  296. startActivity(new Intent(LoginActivity.this, CheckInActivity.class));
  297. finish();
  298. }
  299.  
  300. @Override
  301. public void onCancelled(DatabaseError databaseError) {
  302. Log.d("DatabaseCancelled", "Database returned canceled" + databaseError.toString());
  303. }
  304. });
  305. }
  306.  
  307. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement