private void phoneNumberVerificationCB() { mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { Log.d(TAG, "onVerificationCompleted:" + credential); credent = credential; } @Override public void onVerificationFailed(FirebaseException e) { Log.w(TAG, "onVerificationFailed", e); if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } } }; }
/** * Method to handle sign in; * @param v * @param phoneAuthCredential */ private void signIn(View v, PhoneAuthCredential phoneAuthCredential) { auth.signInWithCredential(phoneAuthCredential) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { redirectToMainActivity(); } else { if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid // [START_EXCLUDE silent] verificationCodeEditext.setError("Invalid code."); // [END_EXCLUDE] } } } }); }
private void onVerificationSuccess(@NonNull final PhoneAuthCredential phoneAuthCredential) { if (TextUtils.isEmpty(phoneAuthCredential.getSmsCode())) { signIn(phoneAuthCredential); } else { //Show Fragment if it is not already visible showSubmitCodeFragment(); SubmitConfirmationCodeFragment submitConfirmationCodeFragment = getSubmitConfirmationCodeFragment(); showLoadingDialog(getString(R.string.fui_retrieving_sms)); if (submitConfirmationCodeFragment != null) { submitConfirmationCodeFragment.setConfirmationCode(String.valueOf (phoneAuthCredential.getSmsCode())); } signIn(phoneAuthCredential); } }
private void signInWithVerificationId(final String verificationId, final String code, final CallbackContext callbackContext) { final PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); this.signinCallback = callbackContext; cordova.getThreadPool().execute(new Runnable() { @Override public void run() { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(cordova.getActivity(), FirebaseAuthenticationPlugin.this); } else { user.updatePhoneNumber(credential) .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<Void>() { @Override public void onComplete(Task<Void> task) { if (task.isSuccessful()) { callbackContext.success(getProfileData(firebaseAuth.getCurrentUser())); } else { callbackContext.error(task.getException().getMessage()); } } }); } } }); }
private void verifyPhoneNumber(final String phoneNumber, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { phoneAuthProvider.verifyPhoneNumber(phoneNumber, 0, MILLISECONDS, cordova.getActivity(), new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { firebaseAuth.signInWithCredential(credential); } else { user.updatePhoneNumber(credential); } callbackContext.success(""); } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) { callbackContext.success(verificationId); } @Override public void onVerificationFailed(FirebaseException e) { callbackContext.error(e.getMessage()); } } ); } }); }
private void signInWithPhoneAuthCredential(final PhoneAuthCredential credential) { hud.show(); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { hud.dismiss(); if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = task.getResult().getUser(); user.updatePhoneNumber(credential); startActivity(new Intent(RegisterPhoneActivity.this, RegisterUserActivity.class)); RegisterPhoneActivity.this.finish(); } else { // Sign in failed, display a message and update the UI Log.w(TAG, "signInWithCredential:failure", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid Toast.makeText(RegisterPhoneActivity.this, "The verification code entered was invalid", Toast.LENGTH_SHORT).show(); } } } }); }
private void verify(View v) { if (verificationCodeEditext.length() == 0) { Snackbar.make(v, R.string.insertcode, Snackbar.LENGTH_LONG) .show(); return; } String code = verificationCodeEditext.getText().toString(); PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); signIn(v, credential); }
private void verifyPhoneNumber(final String phoneNumber, final long timeout, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { phoneAuthProvider.verifyPhoneNumber(phoneNumber, timeout, MILLISECONDS, cordova.getActivity(), new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { firebaseAuth.signInWithCredential(credential); } else { user.updatePhoneNumber(credential); } } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) { callbackContext.success(verificationId); } @Override public void onVerificationFailed(FirebaseException e) { callbackContext.error(e.getMessage()); } } ); } }); }
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = task.getResult().getUser(); // [START_EXCLUDE] updateUI(STATE_SIGNIN_SUCCESS, user); // [END_EXCLUDE] } else { // Sign in failed, display a message and update the UI Log.w(TAG, "signInWithCredential:failure", task.getException()); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid // [START_EXCLUDE silent] mVerificationField.setError("Invalid code."); // [END_EXCLUDE] } // [START_EXCLUDE silent] // Update UI updateUI(STATE_SIGNIN_FAILED); // [END_EXCLUDE] } } }); }
/** * updates the current phone number for the given user. * * @param firebaseUser current firebaseUser instance. * @param phoneAuthCredential new phone credential. * @return a {@link Completable} if the task is complete successfully. */ @NonNull public static Completable updatePhoneNumber(@NonNull final FirebaseUser firebaseUser, @NonNull final PhoneAuthCredential phoneAuthCredential) { return Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter emitter) throws Exception { RxCompletableHandler.assignOnTask(emitter, firebaseUser.updatePhoneNumber(phoneAuthCredential)); } }); }
private void sendCode(String phoneNumber, boolean forceResend) { mPhoneNumber = phoneNumber; mVerificationState = VerificationState.VERIFICATION_STARTED; getAuthHelper().getPhoneAuthProvider().verifyPhoneNumber( phoneNumber, AUTO_RETRIEVAL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS, this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) { if (!mIsDestroyed) { PhoneActivity.this.onVerificationSuccess(phoneAuthCredential); } } @Override public void onVerificationFailed(FirebaseException ex) { if (!mIsDestroyed) { PhoneActivity.this.onVerificationFailed(ex); } } @Override public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) { mVerificationId = verificationId; mForceResendingToken = forceResendingToken; if (!mIsDestroyed) { PhoneActivity.this.onCodeSent(); } } }, forceResend ? mForceResendingToken : null); }
@Override protected void onCreate(Bundle savedInstanceState) { PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks; super.onCreate(savedInstanceState); setContentView(R.layout.activity_otp); sentNumber="INVALID"; //Check for the OTP mCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { sentNumber=phoneAuthCredential.getSmsCode(); Toasty.success(OTP.this, "Verification Success", Toast.LENGTH_SHORT).show(); moveToNextActivity(); } @Override public void onVerificationFailed(FirebaseException e) { Toasty.error(OTP.this, "Invalid OTP", Toast.LENGTH_SHORT).show(); } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) { // Log.d(TAG, "onCodeSent:" + verificationId); Toasty.info(OTP.this, "OTP has been send to your number", Toast.LENGTH_SHORT).show(); // Save verification ID and resending token so we can use them later mVerificationId = verificationId; mResendToken = token; } }; //Phone Auth Parameters PhoneAuthProvider.getInstance().verifyPhoneNumber( LocalDB.getPhoneNumber(), 60, java.util.concurrent.TimeUnit.SECONDS, OTP.this, mCallbacks); if(!isNetworkAvailable()) { Toasty.warning(OTP.this,"Please Check Your Internet Connection and Try Again", Toast.LENGTH_SHORT).show(); } }
private void verifyPhoneNumber(String phoneNumber){ if (!isValid){ Toast.makeText(this, "Invalid Phone number!", Toast.LENGTH_SHORT).show(); return; } hud.show(); 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 verification without // user action. Log.d(TAG, "onVerificationCompleted:" + credential); hud.dismiss(); signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in an invalid request for verification is made, // for instance if the the phone number format is not valid. Toast.makeText(RegisterPhoneActivity.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request Toast.makeText(RegisterPhoneActivity.this, "Invalid mobile number", Toast.LENGTH_SHORT).show(); } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded Toast.makeText(RegisterPhoneActivity.this, "The SMS quota for the project has been exceeded", Toast.LENGTH_SHORT).show(); } // Show a message and update the UI hud.dismiss(); } @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 phoneVerficationID = verificationId; resendToken = token; Toast.makeText(RegisterPhoneActivity.this, getString(R.string.register_verify_sent), Toast.LENGTH_SHORT).show(); hud.dismiss(); startResendTimer(); } }; PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, 60, TimeUnit.SECONDS, this, mCallbacks); }
/** * Method to handle sign up process * * @param v */ private void signUp(final View v) { if (phoneNoEditext.length() == 0) { // if phone no field empty Snackbar.make(v, R.string.insertphoneno, Snackbar.LENGTH_LONG) .show(); return; } String phoneNumber = phoneNoEditext.getText().toString(); // Copy code from google // https://firebase.google.com/docs/auth/android/phone-auth // code to verify phone number. PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { signIn(v, phoneAuthCredential); } @Override public void onVerificationFailed(FirebaseException e) { if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // [START_EXCLUDE] phoneNoEditext.setError("Invalid phone number."); // [END_EXCLUDE] } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // [START_EXCLUDE] Snackbar.make(findViewById(android.R.id.content), "Quota exceeded.", Snackbar.LENGTH_SHORT).show(); // [END_EXCLUDE] } } @Override public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(s, forceResendingToken); verificationId = s; showVerificationLayout(); } }); }
private void verifyPhoneNumberWithCode(String verificationId, String code) { // [START verify_with_code] PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); // [END verify_with_code] signInWithPhoneAuthCredential(credential); }
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: // Initialized state, show only the phone number field and start button enableViews(mStartButton, mPhoneNumberField); disableViews(mVerifyButton, mResendButton, mVerificationField); mDetailText.setText(null); break; case STATE_CODE_SENT: // Code sent state, show the verification field, the enableViews(mVerifyButton, mResendButton, mPhoneNumberField, mVerificationField); disableViews(mStartButton); mDetailText.setText(R.string.status_code_sent); break; case STATE_VERIFY_FAILED: // Verification has failed, show all options enableViews(mStartButton, mVerifyButton, mResendButton, mPhoneNumberField, mVerificationField); mDetailText.setText(R.string.status_verification_failed); break; case STATE_VERIFY_SUCCESS: // Verification has succeeded, proceed to firebase sign in disableViews(mStartButton, mVerifyButton, mResendButton, mPhoneNumberField, mVerificationField); mDetailText.setText(R.string.status_verification_succeeded); // Set the verification text based on the credential if (cred != null) { if (cred.getSmsCode() != null) { mVerificationField.setText(cred.getSmsCode()); } else { mVerificationField.setText(R.string.instant_validation); } } break; case STATE_SIGNIN_FAILED: // No-op, handled by sign-in check mDetailText.setText(R.string.status_sign_in_failed); break; case STATE_SIGNIN_SUCCESS: // Np-op, handled by sign-in check break; } if (user == null) { // Signed out mPhoneNumberViews.setVisibility(View.VISIBLE); mSignedInViews.setVisibility(View.GONE); mStatusText.setText(R.string.signed_out); } else { // Signed in mPhoneNumberViews.setVisibility(View.GONE); mSignedInViews.setVisibility(View.VISIBLE); enableViews(mPhoneNumberField, mVerificationField); mPhoneNumberField.setText(null); mVerificationField.setText(null); mStatusText.setText(R.string.signed_in); mDetailText.setText(getString(R.string.firebase_status_fmt, user.getUid())); } }