-
Notifications
You must be signed in to change notification settings - Fork 22
/
Notes (Firebase Phone Auth).txt
649 lines (529 loc) · 23.8 KB
/
Notes (Firebase Phone Auth).txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/////// CustomBaseActivity.java ////////
public class CustomBaseActivity extends AppCompatActivity {
public ProgressDialog progressDialog;
public ActionBar actionBar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = getSupportActionBar();
}
public void showProgress() {
showProgress(R.string.loading);
}
public void showProgress(int message) {
hideProgress();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(message));
progressDialog.setCancelable(false);
progressDialog.show();
}
public void hideProgress() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
public void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void showSnackBar(String message) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
message, Snackbar.LENGTH_LONG);
snackbar.show();
}
public void showSnackBar(int messageId) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
messageId, Snackbar.LENGTH_LONG);
snackbar.show();
}
public void showSnackBar(View view, int messageId) {
Snackbar snackbar = Snackbar.make(view, messageId, Snackbar.LENGTH_LONG);
snackbar.show();
}
protected void showSnackBar(String message, View view) {
Snackbar snackBar =
Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
View sbView = snackBar.getView();
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
snackBar.show();
}
public void showWarningDialog(int messageId) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(messageId);
builder.setPositiveButton(R.string.button_ok, null);
builder.show();
}
public void showWarningDialog(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setPositiveButton(R.string.button_ok, null);
builder.show();
}
public void exitWarningDialog(){
AlertDialog.Builder Alert_Conn_Error = new AlertDialog.Builder(this);
Alert_Conn_Error.setMessage("Check your Internet Connection..");
Alert_Conn_Error.setTitle("Connection Error");
Alert_Conn_Error.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
Alert_Conn_Error.show();
}
public boolean hasInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public boolean checkInternetConnection() {
boolean hasInternetConnection = hasInternetConnection();
if (!hasInternetConnection) {
showWarningDialog(R.string.msg_no_internet_connection);
}
return hasInternetConnection;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
}
return (super.onOptionsItemSelected(menuItem));
}
}
////////////////////////////// MainActivity.java /////////////////////////////////////////
public class LoginTestActivity extends CustomBaseActivity implements View.OnClickListener {
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener firebaseAuthListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseDatabase mFirebaseDatabase;
private static final String TAG = "PhoneAuthActivity";
private static final String KEY_VERIFY_IN_PROGRESS = "key_verify_in_progress";
private static final int STATE_INITIALIZED = 1;
private static final int STATE_CODE_SENT = 2;
private static final int STATE_VERIFY_FAILED = 3;
private static final int STATE_VERIFY_SUCCESS = 4;
private static final int STATE_SIGNIN_FAILED = 5;
private static final int STATE_SIGNIN_SUCCESS = 6;
private boolean mVerificationInProgress = false;
private String mVerificationId,mPhoneNumber,myCCP;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private ViewGroup mPhoneNumberViews;
private ViewGroup mVerifyViews;
private CircularMorphLayout cmLayout,cmlVerifyLayout;
private TextView mDetailText,mStartButtonTxt,tvPhoneNumber;
private ImageView editPhoneNumber;
private EditText mPhoneNumberField;
//private EditText mVerificationField;
private ConstraintLayout layoutRegistration,layoutVerification;
private TextView tvVerify;
private Button mResendButton;
//private Button mSignOutButton;
ProgressBar progressBar, pbVerify;
Pinview otp;
CountryCodePicker ccp;
CountDownTimer countdownTimer;
@Override
protected void onDestroy() {
super.onDestroy();
if (countdownTimer != null) {
countdownTimer.cancel();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_test);
if (savedInstanceState != null) {
onRestoreInstanceState(savedInstanceState);
}
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser!=null) {
startActivity(new Intent(LoginTestActivity.this, profileActivity.class));
finish();
}else {
}
progressBar = (ProgressBar) findViewById(R.id.progressBar);
pbVerify=(ProgressBar)findViewById(R.id.pb_verifying);
layoutRegistration = (ConstraintLayout)findViewById(R.id.layout_regis);
layoutVerification =(ConstraintLayout)findViewById(R.id.layout_verify);
mDetailText = (TextView) findViewById(R.id.detail);
tvPhoneNumber =(TextView)findViewById(R.id.tv_phone_number);
mPhoneNumberField = (EditText) findViewById(R.id.et_phone_number);
//mVerificationField = (EditText) findViewById(R.id.field_verification_code);
otp = (Pinview)findViewById(R.id.pinview);
ccp = (CountryCodePicker)findViewById(R.id.cc_country_code);
cmLayout = (CircularMorphLayout)findViewById(R.id.cml_proceed_layout);
cmlVerifyLayout=(CircularMorphLayout)findViewById(R.id.cml_verify_layout);
mStartButtonTxt = (TextView)findViewById(R.id.tv_proceed);
tvVerify = (TextView) findViewById(R.id.tv_verify);
editPhoneNumber = (ImageView)findViewById(R.id.ib_edit_number);
mResendButton =(Button)findViewById(R.id.bt_resend_code);
mResendButton.setOnClickListener(this);
mStartButtonTxt.setOnClickListener(this);
editPhoneNumber.setOnClickListener(this);
tvVerify.setOnClickListener(this);
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verificaiton without
// user action.
Log.d(TAG, "onVerificationCompleted:" + credential);
mVerificationInProgress = false;
updateUI(STATE_VERIFY_SUCCESS, credential);
signInWithPhoneAuthCredential(credential);
}
@Override
public void onVerificationFailed(FirebaseException e) {
Log.w(TAG, "onVerificationFailed", e);
mVerificationInProgress = false;
setStartProgressVisibility(false);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
mPhoneNumberField.setError("Invalid phone number.");
layoutVerification.setVisibility(View.GONE);
layoutRegistration.setVisibility(View.VISIBLE);
} else if (e instanceof FirebaseTooManyRequestsException) {
showSnackBar(R.string.msg_sms_verification_limit_exceeded);
layoutVerification.setVisibility(View.GONE);
layoutRegistration.setVisibility(View.VISIBLE);
}
else {
showSnackBar(R.string.msg_encountered_an_unexpected_error);
}
updateUI(STATE_VERIFY_FAILED);
}
@Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.d(TAG, "onCodeSent:" + verificationId);
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
updateUI(STATE_CODE_SENT);
}
};
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
if (mVerificationInProgress && validatePhoneNumber()) {
startPhoneNumberVerification(mPhoneNumberField.getText().toString());
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_VERIFY_IN_PROGRESS, mVerificationInProgress);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mVerificationInProgress = savedInstanceState.getBoolean(KEY_VERIFY_IN_PROGRESS);
}
private void startPhoneNumberVerification(String phoneNumber) {
if (!mVerificationInProgress){
setStartProgressVisibility(true);
mPhoneNumber = phoneNumber;
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
mVerificationInProgress = true;
}else {
showSnackBar("Please wait! Verification already in progress....");
}
}
private void setStartProgressVisibility(boolean isVisible) {
if (isVisible) {
cmLayout.revealFrom(mStartButtonTxt.getWidth() / 2f,
mStartButtonTxt.getHeight() / 2f,
mStartButtonTxt.getWidth() / 2f,
mStartButtonTxt.getHeight() / 2f).setListener(
() -> {
mStartButtonTxt.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}).start();
} else {
mStartButtonTxt.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
cmLayout.reverse();
}
}
private void setVerifyProgressVisibility(boolean isVisible) {
if (isVisible) {
cmlVerifyLayout.revealFrom(tvVerify.getWidth() / 2f,
tvVerify.getHeight() / 2f,
tvVerify.getWidth() / 2f,
tvVerify.getHeight() / 2f).setListener(
() -> {
tvVerify.setVisibility(View.GONE);
pbVerify.setVisibility(View.VISIBLE);
}).start();
} else {
tvVerify.setVisibility(View.VISIBLE);
pbVerify.setVisibility(View.GONE);
cmlVerifyLayout.reverse();
}
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
fetchUser();
FirebaseUser user = task.getResult().getUser();
updateUI(STATE_SIGNIN_SUCCESS, user);
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
showSnackBar("Invalid code.");
}
updateUI(STATE_SIGNIN_FAILED);
}
}
});
}
private void fetchUser() {
String UserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference userDetailDbReference = mFirebaseDatabase.getReference().child(FireBaseConstants.USERS).child(UserId);
userDetailDbReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
setVerifyProgressVisibility(false);
User user = null;
if (dataSnapshot.exists()) {
user = dataSnapshot.getValue(User.class);
}
onSignInSuccess(user);
}
@Override
public void onCancelled(DatabaseError databaseError) {
setVerifyProgressVisibility(false);
setTitle(getString(R.string.verification));
layoutVerification.setVisibility(View.VISIBLE);
layoutRegistration.setVisibility(View.GONE);
showSnackBar(R.string.msg_encountered_an_unexpected_error);
}
});
}
private void onSignInSuccess(User user) {
if (Util.isValidUser(user) == 0) {
//mSharedPreferenceManager.put(SharedPrefConstants.IS_USER_DETAILS_ENTERED, true);
showSnackBar("Authentication Successful");
} else {
startActivity(new Intent(LoginTestActivity.this, profileActivity.class));
finish();
}
}
private void updateUI(int uiState) {
updateUI(uiState, mAuth.getCurrentUser(), null);
}
private void updateUI(FirebaseUser user) {
if (user != null) {
mDetailText.setText(user.getUid());
/*
Intent intent = new Intent(PhoneLogin.this, MapView.class);
startActivity(intent);
finish();
*/
//updateUI(STATE_SIGNIN_SUCCESS, user);
} else {
updateUI(STATE_INITIALIZED);
}
}
private void updateUI(int uiState, FirebaseUser user) {
updateUI(uiState, user, null);
}
private void updateUI(int uiState, PhoneAuthCredential cred) {
updateUI(uiState, null, cred);
}
private void updateUI(int uiState, FirebaseUser user, PhoneAuthCredential cred) {
switch (uiState) {
case STATE_INITIALIZED:
mDetailText.setText("Please verify your phone first!");
break;
case STATE_CODE_SENT:
//progressBar.setVisibility(View.INVISIBLE);
setStartProgressVisibility(false);
setTitle(getString(R.string.verification));
layoutVerification.setVisibility(View.VISIBLE);
layoutRegistration.setVisibility(View.GONE);
startCountdown();
mDetailText.setText("Code Sent");
mDetailText.setTextColor(Color.parseColor("#43a047"));
break;
case STATE_VERIFY_FAILED:
if (countdownTimer != null) {
countdownTimer.cancel();
}
setVerifyProgressVisibility(false);
mDetailText.setText("Verification failed");
mDetailText.setTextColor(Color.parseColor("#dd2c00"));
progressBar.setVisibility(View.INVISIBLE);
break;
case STATE_VERIFY_SUCCESS:
mDetailText.setText("Verfication Sucessfull");
mDetailText.setTextColor(Color.parseColor("#43a047"));
progressBar.setVisibility(View.INVISIBLE);
// Set the verification text based on the credential
if (cred != null) {
if (cred.getSmsCode() != null) {
// mVerificationField.setText(cred.getSmsCode());
otp.setValue(cred.getSmsCode());
} else {
showSnackBar("Instant Validation");
//mVerificationField.setTextColor(Color.parseColor("#4bacb8"));
}
}
break;
case STATE_SIGNIN_FAILED:
// No-op, handled by sign-in check
mDetailText.setText("Sign In Failed !");
mDetailText.setTextColor(Color.parseColor("#dd2c00"));
progressBar.setVisibility(View.INVISIBLE);
setVerifyProgressVisibility(false);
break;
case STATE_SIGNIN_SUCCESS:
// Np-op, handled by sign-in check
//mStatusText.setText(R.string.signed_in);
break;
}
if (user == null) {
// Signed out
//mPhoneNumberViews.setVisibility(View.VISIBLE);
// mVerifyViews.setVisibility(View.VISIBLE);
// mStatusText.setText(R.string.signed_out);
;
} else {
// Signed in
//mPhoneNumberViews.setVisibility(View.GONE);
}
}
private void startCountdown() {
tvPhoneNumber.setText(mPhoneNumber);
setResendButtonEnabled(false);
countdownTimer = new CountDownTimer(60 * 1000, 1000) {
@Override public void onTick(long millisUntilFinished) {
setResendButtonTimerCount(millisUntilFinished / 1000);
}
@Override public void onFinish() {
setResendButtonEnabled(true);
}
}.start();
}
public void setResendButtonEnabled(boolean isEnabled) {
if (isEnabled) {
mResendButton.setEnabled(true);
mResendButton.setText(R.string.resend_code);
} else {
mResendButton.setEnabled(false);
}
}
private void setResendButtonTimerCount(long secondsRemaining) {
mResendButton.setText(
String.format(Locale.ENGLISH, getString(R.string.resend_code_timer), secondsRemaining));
}
private boolean validatePhoneNumber() {
String phoneNumber = mPhoneNumberField.getText().toString();
if (TextUtils.isEmpty(phoneNumber)) {
mPhoneNumberField.setError("Invalid phone number.");
//mPhoneNumberField.setTextColor(Color.parseColor("#ff1744"));
return false;
}
return true;
}
private void enableViews(View... views) {
for (View v : views) {
v.setEnabled(true);
}
}
private void disableViews(View... views) {
for (View v : views) {
v.setEnabled(false);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_proceed:
if (hasInternetConnection()) {
String phone = mPhoneNumberField.getText().toString();
myCCP = ccp.getSelectedCountryCode();
if (Util.isValidPhoneNumber(phone)){
progressBar.setVisibility(View.VISIBLE);
startPhoneNumberVerification(Util.getPhoneNumberWithPlus(phone, myCCP));
}
else {
mPhoneNumberField.setError(getText(R.string.msg_invalid_phone_number));
}
}else {
showSnackBar(R.string.msg_no_internet_connection);
}
break;
case R.id.tv_verify:
String code = otp.getValue().toString();
if (TextUtils.isEmpty(code)) {
showSnackBar("Please enter the phone code");
return;
}
setVerifyProgressVisibility(true);
verifyPhoneNumberWithCode(mVerificationId, code);
break;
case R.id.bt_resend_code:
showSnackBar(R.string.msg_otp_has_been_sent);
startPhoneNumberVerification(mPhoneNumber);
break;
case R.id.ib_edit_number:
showEditPhoneDialog();
break;
}
}
private void showEditPhoneDialog() {
new AlertDialog.Builder(this)
.setMessage(
String.format(
getString(R.string.msg_currently_verifying_number),
otp.getValue(),mPhoneNumber))
.setCancelable(false)
.setPositiveButton(android.R.string.yes,
(dialog, which) -> onEditPhoneNumberActionYes())
.setNegativeButton(android.R.string.cancel, (dialog, which) -> dialog.dismiss())
.show();
}
private void onEditPhoneNumberActionYes() {
mVerificationInProgress = false;
if (countdownTimer != null) {
countdownTimer.cancel();
}
setTitle(getString(R.string.app_name));
layoutVerification.setVisibility(View.GONE);
layoutRegistration.setVisibility(View.VISIBLE);
}
}