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 // ... } } }; }
@Override protected void pluginInitialize() { Log.d(TAG, "Starting Firebase Authentication plugin"); this.firebaseAuth = FirebaseAuth.getInstance(); this.phoneAuthProvider = PhoneAuthProvider.getInstance(); Context context = this.cordova.getActivity().getApplicationContext(); String defaultClientId = getDefaultClientId(context); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(defaultClientId) .requestEmail() .requestProfile() .build(); googleApiClient = new GoogleApiClient.Builder(context) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); googleApiClient.connect(); //firebaseAuth = FirebaseAuth.getInstance(); //firebaseAuth.addAuthStateListener(this); }
/** * Translate a Firebase Auth provider ID (such as {@link GoogleAuthProvider#PROVIDER_ID}) to a * Credentials API account type (such as {@link IdentityProviders#GOOGLE}). */ public static String providerIdToAccountType(@AuthUI.SupportedProvider @NonNull String providerId) { switch (providerId) { case GoogleAuthProvider.PROVIDER_ID: return IdentityProviders.GOOGLE; case FacebookAuthProvider.PROVIDER_ID: return IdentityProviders.FACEBOOK; case TwitterAuthProvider.PROVIDER_ID: return IdentityProviders.TWITTER; case PhoneAuthProvider.PROVIDER_ID: return PHONE_IDENTITY; // The account type for email/password creds is null case EmailAuthProvider.PROVIDER_ID: default: return null; } }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testVerifyPhoneNumberNoMsgException_showsAlertDialog() { reset(AuthHelperShadow.getPhoneAuthProvider()); mActivity.verifyPhoneNumber(PHONE, false); verify(AuthHelperShadow.getPhoneAuthProvider()).verifyPhoneNumber( eq(PHONE), eq(AUTO_RETRIEVAL_TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS), eq(mActivity), callbacksArgumentCaptor.capture(), (PhoneAuthProvider.ForceResendingToken) isNull()); PhoneAuthProvider.OnVerificationStateChangedCallbacks onVerificationStateChangedCallbacks = callbacksArgumentCaptor.getValue(); onVerificationStateChangedCallbacks.onVerificationFailed( new FirebaseAuthException("some_code", "custom_message")); assertTrue(mActivity.getAlertDialog().isShowing()); assertEquals(FirebaseAuthError.ERROR_UNKNOWN.getDescription(), getAlertDialogMessage()); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testAutoVerify() { reset(AuthHelperShadow.getPhoneAuthProvider()); reset(AuthHelperShadow.getSaveSmartLockInstance(null)); reset(AuthHelperShadow.getFirebaseAuth()); when(AuthHelperShadow.getCurrentUser().getPhoneNumber()).thenReturn(PHONE); when(AuthHelperShadow.getCurrentUser().getEmail()).thenReturn(null); when(AuthHelperShadow.getFirebaseAuth().signInWithCredential(any(AuthCredential.class))) .thenReturn(new AutoCompleteTask<>(FakeAuthResult.INSTANCE, true, null)); mActivity.verifyPhoneNumber(PHONE, false); verify(AuthHelperShadow.getPhoneAuthProvider()).verifyPhoneNumber( eq(PHONE), eq(AUTO_RETRIEVAL_TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS), eq(mActivity), callbacksArgumentCaptor.capture(), (PhoneAuthProvider.ForceResendingToken) isNull()); PhoneAuthProvider.OnVerificationStateChangedCallbacks onVerificationStateChangedCallbacks = callbacksArgumentCaptor.getValue(); onVerificationStateChangedCallbacks.onVerificationCompleted(credential); verify(AuthHelperShadow.getFirebaseAuth()).signInWithCredential(any(AuthCredential.class)); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testSMSAutoRetrieval() { reset(AuthHelperShadow.getPhoneAuthProvider()); reset(AuthHelperShadow.getSaveSmartLockInstance(null)); when(credential.getSmsCode()).thenReturn("123456"); when(AuthHelperShadow.getCurrentUser().getPhoneNumber()).thenReturn(PHONE); when(AuthHelperShadow.getCurrentUser().getEmail()).thenReturn(null); when(AuthHelperShadow.getFirebaseAuth().signInWithCredential(any(AuthCredential.class))) .thenReturn(new AutoCompleteTask<>(FakeAuthResult.INSTANCE, true, null)); PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks = testSendConfirmationCode(); callbacks.onVerificationCompleted(credential); SpacedEditText mConfirmationCodeEditText = mActivity.findViewById(R.id.confirmation_code); //verify confirmation code set assertEquals("1 2 3 4 5 6", mConfirmationCodeEditText.getText().toString()); //verify credential saves verify(AuthHelperShadow.getFirebaseAuth()).signInWithCredential(credential); }
@Override protected void pluginInitialize() { Log.d(TAG, "Starting Firebase Authentication plugin"); this.firebaseAuth = FirebaseAuth.getInstance(); this.phoneAuthProvider = PhoneAuthProvider.getInstance(); }
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 resendVerificationCode(String phoneNumber, PhoneAuthProvider.ForceResendingToken token) { PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) mCallbacks, // OnVerificationStateChangedCallbacks token); // ForceResendingToken from callbacks }
private void startPhoneNumberVerification(String phoneNumber) { // [START start_phone_auth] PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 120, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks // [END start_phone_auth] mVerificationInProgress = true; }
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 startPhoneNumberVerification(String phoneNumber) { // [START start_phone_auth] PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks // [END start_phone_auth] mVerificationInProgress = true; }
public void submitConfirmationCode(@NonNull String confirmationCode) { if (TextUtils.isEmpty(mVerificationId) || TextUtils.isEmpty(confirmationCode)) { // This situation should never happen except in the case of an extreme race // condition, so we will just ignore the submission. // See: https://github.com/firebase/FirebaseUI-Android/issues/922 Log.w(PHONE_VERIFICATION_LOG_TAG, String.format("submitConfirmationCode: mVerificationId is %s ; " + "confirmationCode is %s", TextUtils.isEmpty(mVerificationId) ? "empty" : "not empty", TextUtils.isEmpty(confirmationCode) ? "empty" : "not empty")); return; } showLoadingDialog(getString(R.string.fui_verifying)); signIn(PhoneAuthProvider.getCredential(mVerificationId, confirmationCode)); }
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); }
private void finish(FirebaseUser user) { IdpResponse response = new IdpResponse.Builder( new User.Builder(PhoneAuthProvider.PROVIDER_ID, null) .setPhoneNumber(user.getPhoneNumber()) .build()) .build(); finish(RESULT_OK, response.toIntent()); }
@AuthUI.SupportedProvider public static String accountTypeToProviderId(@NonNull String accountType) { switch (accountType) { case IdentityProviders.GOOGLE: return GoogleAuthProvider.PROVIDER_ID; case IdentityProviders.FACEBOOK: return FacebookAuthProvider.PROVIDER_ID; case IdentityProviders.TWITTER: return TwitterAuthProvider.PROVIDER_ID; case PHONE_IDENTITY: return PhoneAuthProvider.PROVIDER_ID; default: return null; } }
private void startAuthMethodChoice() { FlowParameters flowParams = getFlowParams(); List<AuthUI.IdpConfig> idpConfigs = flowParams.providerInfo; // If there is only one provider selected, launch the flow directly if (idpConfigs.size() == 1) { AuthUI.IdpConfig firstIdpConfig = idpConfigs.get(0); String firstProvider = firstIdpConfig.getProviderId(); switch (firstProvider) { case EmailAuthProvider.PROVIDER_ID: // Go directly to email flow startActivityForResult( EmailActivity.createIntent(getContext(), flowParams), RC_EMAIL_FLOW); break; case PhoneAuthProvider.PROVIDER_ID: // Go directly to phone flow Bundle params = firstIdpConfig.getParams(); Intent phoneActivityIntent = PhoneActivity .createIntent(getContext(), flowParams, params); startActivityForResult( phoneActivityIntent, RC_PHONE_FLOW); break; default: // Launch IDP flow redirectToIdpSignIn(null, ProviderUtils.providerIdToAccountType(firstProvider)); break; } } else { startActivityForResult( AuthMethodPickerActivity.createIntent( getContext(), flowParams), RC_AUTH_METHOD_PICKER); } getDialogHolder().dismissDialog(); }
@Test @Config(shadows = {AuthHelperShadow.class}) public void testVerifyPhoneNumberInvalidPhoneException_showsInlineError() { reset(AuthHelperShadow.getPhoneAuthProvider()); mActivity.verifyPhoneNumber(PHONE, false); //was dialog displayed assertEquals( mActivity.getString(R.string.fui_verifying), mActivity.mProgressDialog.mMessageView.getText()); //was upstream method invoked verify(AuthHelperShadow.getPhoneAuthProvider()).verifyPhoneNumber( eq(PHONE), eq(AUTO_RETRIEVAL_TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS), eq(mActivity), callbacksArgumentCaptor.capture(), (PhoneAuthProvider.ForceResendingToken) isNull()); PhoneAuthProvider.OnVerificationStateChangedCallbacks onVerificationStateChangedCallbacks = callbacksArgumentCaptor.getValue(); onVerificationStateChangedCallbacks.onVerificationFailed( new FirebaseAuthException( FirebaseAuthError.ERROR_INVALID_PHONE_NUMBER.toString(), "any_message")); //was error displayed assertEquals(mPhoneLayout.getError(), mActivity.getString(R.string.fui_invalid_phone_number)); }
private PhoneAuthProvider.OnVerificationStateChangedCallbacks testSendConfirmationCode() { mActivity.verifyPhoneNumber(PHONE, false); verify(AuthHelperShadow.getPhoneAuthProvider()).verifyPhoneNumber( eq(PHONE), eq(AUTO_RETRIEVAL_TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS), eq(mActivity), callbacksArgumentCaptor.capture(), (PhoneAuthProvider.ForceResendingToken) isNull()); PhoneAuthProvider.OnVerificationStateChangedCallbacks onVerificationStateChangedCallbacks = callbacksArgumentCaptor.getValue(); onVerificationStateChangedCallbacks.onCodeSent(verificationId, forceResendingToken); //Force postDelayed runnables to completed on looper ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); SubmitConfirmationCodeFragment fragment = (SubmitConfirmationCodeFragment) mActivity .getSupportFragmentManager().findFragmentByTag(SubmitConfirmationCodeFragment.TAG); assertNotNull(fragment); SpacedEditText mConfirmationCodeEditText = mActivity .findViewById(R.id.confirmation_code); assertTrue(mConfirmationCodeEditText.isFocused()); return onVerificationStateChangedCallbacks; }
@Implementation public static PhoneAuthProvider getPhoneAuthProvider() { if (sPhoneAuthProvider == null) { sPhoneAuthProvider = Mockito.mock(PhoneAuthProvider.class); } return sPhoneAuthProvider; }
@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); }
@MainThread private void populateProfile() { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user.getPhotoUrl() != null) { GlideApp.with(this) .load(user.getPhotoUrl()) .fitCenter() .into(mUserProfilePicture); } mUserEmail.setText( TextUtils.isEmpty(user.getEmail()) ? "No email" : user.getEmail()); mUserPhoneNumber.setText( TextUtils.isEmpty(user.getPhoneNumber()) ? "No phone number" : user.getPhoneNumber()); mUserDisplayName.setText( TextUtils.isEmpty(user.getDisplayName()) ? "No display name" : user.getDisplayName()); StringBuilder providerList = new StringBuilder(100); providerList.append("Providers used: "); if (user.getProviders() == null || user.getProviders().isEmpty()) { providerList.append("none"); } else { Iterator<String> providerIter = user.getProviders().iterator(); while (providerIter.hasNext()) { String provider = providerIter.next(); switch (provider) { case GoogleAuthProvider.PROVIDER_ID: providerList.append("Google"); break; case FacebookAuthProvider.PROVIDER_ID: providerList.append("Facebook"); break; case TwitterAuthProvider.PROVIDER_ID: providerList.append("Twitter"); break; case EmailAuthProvider.PROVIDER_ID: providerList.append("Email"); break; case PhoneAuthProvider.PROVIDER_ID: providerList.append("Phone"); break; default: throw new IllegalStateException("Unknown provider: " + provider); } if (providerIter.hasNext()) { providerList.append(", "); } } } mEnabledProviders.setText(providerList); }
public PhoneAuthProvider getPhoneAuthProvider() { return PhoneAuthProvider.getInstance(getFirebaseAuth()); }