com.google.firebase.auth.PhoneAuthProvider Java Examples

The following examples show how to use com.google.firebase.auth.PhoneAuthProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PhoneProviderHandler.java    From capacitor-firebase-auth with MIT License 6 votes vote down vote up
@Override
public void signIn(PluginCall call) {
    if (!call.getData().has("data")) {
        call.reject("The auth data is required");
        return;
    }

    JSObject data = call.getObject("data", new JSObject());

    String phone = data.getString("phone", "");
    if (phone.equalsIgnoreCase("null") || phone.equalsIgnoreCase("")) {
        call.reject("The phone number is required");
        return;
    }

    String code = data.getString("verificationCode", "");
    if(code.equalsIgnoreCase("null") || code.equalsIgnoreCase("")) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber
                (phone, 60, TimeUnit.SECONDS, this.plugin.getActivity(), this.mCallbacks);
    } else {
        AuthCredential credential = PhoneAuthProvider.getCredential(this.mVerificationId, code);
        this.mVerificationCode = code;
        plugin.handleAuthCredentials(credential);
    }
}
 
Example #2
Source File: ProviderUtils.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@NonNull
@AuthUI.SupportedProvider
public static String signInMethodToProviderId(@NonNull String method) {
    switch (method) {
        case GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD:
            return GoogleAuthProvider.PROVIDER_ID;
        case FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD:
            return FacebookAuthProvider.PROVIDER_ID;
        case TwitterAuthProvider.TWITTER_SIGN_IN_METHOD:
            return TwitterAuthProvider.PROVIDER_ID;
        case GithubAuthProvider.GITHUB_SIGN_IN_METHOD:
            return GithubAuthProvider.PROVIDER_ID;
        case PhoneAuthProvider.PHONE_SIGN_IN_METHOD:
            return PhoneAuthProvider.PROVIDER_ID;
        case EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD:
            return EmailAuthProvider.PROVIDER_ID;
        case EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD:
            return EMAIL_LINK_PROVIDER;
        default:
            return method;
    }
}
 
Example #3
Source File: ProviderUtils.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 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 GithubAuthProvider.PROVIDER_ID:
            return GITHUB_IDENTITY;
        case PhoneAuthProvider.PROVIDER_ID:
            return PHONE_IDENTITY;
        // The account type for email/password creds is null
        case EmailAuthProvider.PROVIDER_ID:
        default:
            return null;
    }
}
 
Example #4
Source File: ProviderUtils.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@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 GITHUB_IDENTITY:
            return GithubAuthProvider.PROVIDER_ID;
        case PHONE_IDENTITY:
            return PhoneAuthProvider.PROVIDER_ID;
        default:
            return null;
    }
}
 
Example #5
Source File: ProviderUtils.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
public static String providerIdToProviderName(@NonNull String providerId) {
    switch (providerId) {
        case GoogleAuthProvider.PROVIDER_ID:
            return AuthUI.getApplicationContext().getString(R.string.fui_idp_name_google);
        case FacebookAuthProvider.PROVIDER_ID:
            return AuthUI.getApplicationContext().getString(R.string.fui_idp_name_facebook);
        case TwitterAuthProvider.PROVIDER_ID:
            return AuthUI.getApplicationContext().getString(R.string.fui_idp_name_twitter);
        case GithubAuthProvider.PROVIDER_ID:
            return AuthUI.getApplicationContext().getString(R.string.fui_idp_name_github);
        case PhoneAuthProvider.PROVIDER_ID:
            return AuthUI.getApplicationContext().getString(R.string.fui_idp_name_phone);
        case EmailAuthProvider.PROVIDER_ID:
        case EMAIL_LINK_PROVIDER:
            return AuthUI.getApplicationContext().getString(R.string.fui_idp_name_email);
        default:
            return null;
    }
}
 
Example #6
Source File: SignInKickstarter.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void redirectSignIn(String provider, String id) {
    switch (provider) {
        case EmailAuthProvider.PROVIDER_ID:
            setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException(
                    EmailActivity.createIntent(getApplication(), getArguments(), id),
                    RequestCodes.EMAIL_FLOW)));
            break;
        case PhoneAuthProvider.PROVIDER_ID:
            Bundle args = new Bundle();
            args.putString(ExtraConstants.PHONE, id);
            setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException(
                    PhoneActivity.createIntent(
                            getApplication(),
                            getArguments(),
                            args),
                    RequestCodes.PHONE_FLOW)));
            break;
        default:
            setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException(
                    SingleSignInActivity.createIntent(
                            getApplication(),
                            getArguments(),
                            new User.Builder(provider, id).build()),
                    RequestCodes.PROVIDER_FLOW)));
    }
}
 
Example #7
Source File: PhoneProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignIn_autoUpgradeAnonymousEnabledWithNewUser_expectSuccess() {
    mHandler.getOperation().observeForever(mResponseObserver);
    setupAnonymousUpgrade();

    when(mMockAuth.getCurrentUser().linkWithCredential(mCredential))
            .thenReturn(AutoCompleteTask.forSuccess(FakeAuthResult.INSTANCE));

    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            PhoneAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .build();

    mHandler.startSignIn(mCredential, response);

    verify(mMockAuth.getCurrentUser()).linkWithCredential(mCredential);
    verify(mResponseObserver).onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #8
Source File: MultiFactorSignInActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
private PhoneAuthProvider.OnVerificationStateChangedCallbacks generateCallbacks() {
    return new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            MultiFactorSignInActivity.this.mPhoneAuthCredential = phoneAuthCredential;
            mBinding.finishMfaSignIn.performClick();
            Toast.makeText(
                    MultiFactorSignInActivity.this, "Verification complete!", Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken token) {
            MultiFactorSignInActivity.this.mVerificationId = verificationId;
            mBinding.finishMfaSignIn.setClickable(true);
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(
                    MultiFactorSignInActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
        }
    };
}
 
Example #9
Source File: MultiFactorSignInActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
private View.OnClickListener generateFactorOnClickListener(PhoneMultiFactorInfo phoneMultiFactorInfo) {
    return new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PhoneAuthProvider.verifyPhoneNumber(
                    PhoneAuthOptions.newBuilder()
                            .setActivity(MultiFactorSignInActivity.this)
                            .setMultiFactorSession(mMultiFactorResolver.getSession())
                            .setMultiFactorHint(phoneMultiFactorInfo)
                            .setCallbacks(generateCallbacks())
                            // A timeout of 0 disables SMS-auto-retrieval.
                            .setTimeout(0L, TimeUnit.SECONDS)
                            .build());
        }
    };
}
 
Example #10
Source File: OtpGenerator.java    From GetIntoClub with GNU General Public License v3.0 6 votes vote down vote up
private void StartFirebaseLogin() {

        auth = FirebaseAuth.getInstance();
        mCallback = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

            @Override
            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                Toast.makeText(OtpGenerator.this, "verification completed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                Toast.makeText(OtpGenerator.this, "verification failed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                super.onCodeSent(s, forceResendingToken);
                verificationCode = s;
                Toast.makeText(OtpGenerator.this, "Code sent", Toast.LENGTH_SHORT).show();
                btnSignIn.setVisibility(View.VISIBLE);
                btnGenerateOTP.setVisibility(View.GONE);
            }
        };
    }
 
Example #11
Source File: AuthMethodPickerActivityTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllProvidersArePopulated() {
    // Exclude Facebook until the `NoClassDefFoundError: com/facebook/common/R$style` exception
    // is fixed.
    List<String> providers = Arrays.asList(
            GoogleAuthProvider.PROVIDER_ID,
            TwitterAuthProvider.PROVIDER_ID,
            EmailAuthProvider.PROVIDER_ID,
            PhoneAuthProvider.PROVIDER_ID,
            AuthUI.ANONYMOUS_PROVIDER);

    AuthMethodPickerActivity authMethodPickerActivity = createActivity(providers);

    assertEquals(providers.size(),
            ((LinearLayout) authMethodPickerActivity.findViewById(R.id.btn_holder))
                    .getChildCount());
}
 
Example #12
Source File: verifyPatient.java    From Doctorave with MIT License 6 votes vote down vote up
private void firebasePhoneVerification() {
    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            progressDialog.dismiss();
            Toast.makeText(verifyPatient.this, e.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            progressDialog.dismiss();
            Toast.makeText(verifyPatient.this, "Code Sent ", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(verifyPatient.this, verifyPatient2.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("verificationId", s);
            intent.putExtra("phone", fullPhoneNo);
            startActivity(intent);
        }
    };
}
 
Example #13
Source File: PhoneProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void setupAnonymousUpgrade() {
    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            PhoneAuthProvider.PROVIDER_ID), true);
    mHandler.initializeForTesting(testParams, mMockAuth, null, null);
    when(mMockAuth.getCurrentUser()).thenReturn(mMockUser);
    when(mMockUser.isAnonymous()).thenReturn(true);
}
 
Example #14
Source File: PhoneNumberVerificationHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public void verifyPhoneNumber(final String number, boolean force) {
    setResult(Resource.<PhoneVerification>forLoading());
    getPhoneAuth().verifyPhoneNumber(
            number,
            AUTO_RETRIEVAL_TIMEOUT_SECONDS,
            TimeUnit.SECONDS,
            TaskExecutors.MAIN_THREAD,
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
                    setResult(Resource.forSuccess(new PhoneVerification(
                            number, credential, true)));
                }

                @Override
                public void onVerificationFailed(FirebaseException e) {
                    setResult(Resource.<PhoneVerification>forFailure(e));
                }

                @Override
                public void onCodeSent(@NonNull String verificationId,
                                       @NonNull PhoneAuthProvider.ForceResendingToken token) {
                    mVerificationId = verificationId;
                    mForceResendingToken = token;
                    setResult(Resource.<PhoneVerification>forFailure(
                            new PhoneNumberVerificationRequiredException(number)));
                }
            },
            force ? mForceResendingToken : null);
}
 
Example #15
Source File: AuthMethodPickerActivity.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void populateIdpList(List<IdpConfig> providerConfigs) {

        ViewModelProvider supplier = ViewModelProviders.of(this);
        mProviders = new ArrayList<>();
        for (IdpConfig idpConfig : providerConfigs) {
            @LayoutRes int buttonLayout;

            final String providerId = idpConfig.getProviderId();
            switch (providerId) {
                case GoogleAuthProvider.PROVIDER_ID:
                    buttonLayout = R.layout.fui_idp_button_google;
                    break;
                case FacebookAuthProvider.PROVIDER_ID:
                    buttonLayout = R.layout.fui_idp_button_facebook;
                    break;
                case EMAIL_LINK_PROVIDER:
                case EmailAuthProvider.PROVIDER_ID:
                    buttonLayout = R.layout.fui_provider_button_email;
                    break;
                case PhoneAuthProvider.PROVIDER_ID:
                    buttonLayout = R.layout.fui_provider_button_phone;
                    break;
                case AuthUI.ANONYMOUS_PROVIDER:
                    buttonLayout = R.layout.fui_provider_button_anonymous;
                    break;
                default:
                    if (!TextUtils.isEmpty(
                            idpConfig.getParams().getString(GENERIC_OAUTH_PROVIDER_ID))) {
                        buttonLayout = idpConfig.getParams().getInt(GENERIC_OAUTH_BUTTON_ID);
                        break;
                    }
                    throw new IllegalStateException("Unknown provider: " + providerId);
            }

            View loginButton = getLayoutInflater().inflate(buttonLayout, mProviderHolder, false);
            handleSignInOperation(idpConfig, loginButton);
            mProviderHolder.addView(loginButton);
        }
    }
 
Example #16
Source File: AuthMethodPickerActivityTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testPhoneLoginFlow() {
    List<String> providers = Arrays.asList(PhoneAuthProvider.PROVIDER_ID);

    AuthMethodPickerActivity authMethodPickerActivity = createActivity(providers);

    Button phoneButton = authMethodPickerActivity.findViewById(R.id.phone_button);
    phoneButton.performClick();
    ShadowActivity.IntentForResult nextIntent =
            Shadows.shadowOf(authMethodPickerActivity).getNextStartedActivityForResult();

    assertEquals(
            PhoneActivity.class.getName(),
            nextIntent.intent.getComponent().getClassName());
}
 
Example #17
Source File: SignInKickstarter.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void startAuthMethodChoice() {
    // If there is only one provider selected, launch the flow directly
    if (!getArguments().shouldShowProviderChoice()) {
        AuthUI.IdpConfig firstIdpConfig = getArguments().providers.get(0);
        String firstProvider = firstIdpConfig.getProviderId();
        switch (firstProvider) {
            case EMAIL_LINK_PROVIDER:
            case EmailAuthProvider.PROVIDER_ID:
                setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException(
                        EmailActivity.createIntent(getApplication(), getArguments()),
                        RequestCodes.EMAIL_FLOW)));
                break;
            case PhoneAuthProvider.PROVIDER_ID:
                setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException(
                        PhoneActivity.createIntent(
                                getApplication(), getArguments(), firstIdpConfig.getParams()),
                        RequestCodes.PHONE_FLOW)));
                break;
            default:
                redirectSignIn(firstProvider, null);
                break;
        }
    } else {
        setResult(Resource.<IdpResponse>forFailure(new IntentRequiredException(
                AuthMethodPickerActivity.createIntent(getApplication(), getArguments()),
                RequestCodes.AUTH_PICKER_FLOW)));
    }
}
 
Example #18
Source File: PhoneProviderResponseHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public void startSignIn(@NonNull PhoneAuthCredential credential,
                        @NonNull final IdpResponse response) {
    if (!response.isSuccessful()) {
        setResult(Resource.<IdpResponse>forFailure(response.getError()));
        return;
    }
    if (!response.getProviderType().equals(PhoneAuthProvider.PROVIDER_ID)) {
        throw new IllegalStateException(
                "This handler cannot be used without a phone response.");
    }

    setResult(Resource.<IdpResponse>forLoading());

    AuthOperationManager.getInstance()
            .signInAndLinkWithCredential(getAuth(), getArguments(), credential)
            .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult result) {
                    handleSuccess(response, result);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if (e instanceof FirebaseAuthUserCollisionException) {
                        // With phone auth, this only happens if we are trying to upgrade
                        // an anonymous account using a phone number that is already registered
                        // on another account
                        handleMergeFailure(((FirebaseAuthUserCollisionException) e).getUpdatedCredential());
                    } else {
                        setResult(Resource.<IdpResponse>forFailure(e));
                    }
                }
            });
}
 
Example #19
Source File: AuthViewModelBase.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public void initializeForTesting(FlowParameters parameters,
                                 FirebaseAuth auth,
                                 CredentialsClient client,
                                 PhoneAuthProvider phoneAuth) {
    setArguments(parameters);
    mAuth = auth;
    mCredentialsClient = client;
    mPhoneAuth = phoneAuth;
}
 
Example #20
Source File: PhoneProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    TestHelper.initialize();
    MockitoAnnotations.initMocks(this);

    mHandler = new PhoneProviderResponseHandler((Application) ApplicationProvider.getApplicationContext());
    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            PhoneAuthProvider.PROVIDER_ID));
    mHandler.initializeForTesting(testParams, mMockAuth, null, null);
}
 
Example #21
Source File: AuthViewModelBase.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate() {
    FirebaseApp app = FirebaseApp.getInstance(getArguments().appName);
    mAuth = FirebaseAuth.getInstance(app);
    mPhoneAuth = PhoneAuthProvider.getInstance(mAuth);
    mCredentialsClient = GoogleApiUtils.getCredentialsClient(getApplication());
}
 
Example #22
Source File: PhoneProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignIn_withValidCredentialAndNewUser_expectSuccess() {
    mHandler.getOperation().observeForever(mResponseObserver);

    when(mMockAuth.signInWithCredential(mCredential))
            .thenReturn(AutoCompleteTask.forSuccess(FakeAuthResult.INSTANCE));

    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            PhoneAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .build();

    mHandler.startSignIn(mCredential, response);
    verify(mMockAuth).signInWithCredential(mCredential);
    verify(mResponseObserver).onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #23
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void testPhoneVerify() {
    // [START auth_test_phone_verify]
    String phoneNum = "+16505554567";
    String testVerificationCode = "123456";

    // Whenever verification is triggered with the whitelisted number,
    // provided it is not set for auto-retrieval, onCodeSent will be triggered.
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNum, 30L /*timeout*/, TimeUnit.SECONDS,
            this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

                @Override
                public void onCodeSent(String verificationId,
                                       PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                    // Save the verification id somewhere
                    // ...

                    // The corresponding whitelisted code above should be used to complete sign-in.
                    MainActivity.this.enableUserManuallyInputCode();
                }

                @Override
                public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                    // Sign in with the credential
                    // ...
                }

                @Override
                public void onVerificationFailed(FirebaseException e) {
                     // ...
                }

            });
    // [END auth_test_phone_verify]
}
 
Example #24
Source File: SignedInActivity.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void populateProfile(@Nullable IdpResponse response) {
    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());

    if (response == null) {
        mIsNewUser.setVisibility(View.GONE);
    } else {
        mIsNewUser.setVisibility(View.VISIBLE);
        mIsNewUser.setText(response.isNewUser() ? "New user" : "Existing user");
    }

    List<String> providers = new ArrayList<>();
    if (user.getProviderData().isEmpty()) {
        providers.add(getString(R.string.providers_anonymous));
    } else {
        for (UserInfo info : user.getProviderData()) {
            switch (info.getProviderId()) {
                case GoogleAuthProvider.PROVIDER_ID:
                    providers.add(getString(R.string.providers_google));
                    break;
                case FacebookAuthProvider.PROVIDER_ID:
                    providers.add(getString(R.string.providers_facebook));
                    break;
                case TwitterAuthProvider.PROVIDER_ID:
                    providers.add(getString(R.string.providers_twitter));
                    break;
                case EmailAuthProvider.PROVIDER_ID:
                    providers.add(getString(R.string.providers_email));
                    break;
                case PhoneAuthProvider.PROVIDER_ID:
                    providers.add(getString(R.string.providers_phone));
                    break;
                case EMAIL_LINK_PROVIDER:
                    providers.add(getString(R.string.providers_email_link));
                    break;
                case FirebaseAuthProvider.PROVIDER_ID:
                    // Ignore this provider, it's not very meaningful
                    break;
                default:
                    providers.add(info.getProviderId());
            }
        }
    }

    mEnabledProviders.setText(getString(R.string.used_providers, providers));
}
 
Example #25
Source File: MultiFactorSignInActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void onClickFinishSignIn() {
    if (mPhoneAuthCredential == null) {
        if (isEmpty(mBinding.smsCode.getText().toString())) {
            Toast.makeText(
                    MultiFactorSignInActivity.this, "You need to enter an SMS code.", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        mPhoneAuthCredential =
                PhoneAuthProvider.getCredential(
                        mVerificationId, mBinding.smsCode.getText().toString());
    }
    mMultiFactorResolver
            .resolveSignIn(PhoneMultiFactorGenerator.getAssertion(mPhoneAuthCredential))
            .addOnSuccessListener(
                    new OnSuccessListener<AuthResult>() {
                        @Override
                        public void onSuccess(AuthResult authResult) {
                            setResult(Activity.RESULT_OK);
                            finish();
                        }
                    })
            .addOnFailureListener(
                    new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(
                                    MultiFactorSignInActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
}
 
Example #26
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void testPhoneAutoRetrieve() {
    // [START auth_test_phone_auto]
    // The test phone number and code should be whitelisted in the console.
    String phoneNumber = "+16505554567";
    String smsCode = "123456";

    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    FirebaseAuthSettings firebaseAuthSettings = firebaseAuth.getFirebaseAuthSettings();

    // Configure faking the auto-retrieval with the whitelisted numbers.
    firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode);

    PhoneAuthProvider phoneAuthProvider = PhoneAuthProvider.getInstance();
    phoneAuthProvider.verifyPhoneNumber(
            phoneNumber,
            60L,
            TimeUnit.SECONDS,
            this, /* activity */
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(PhoneAuthCredential credential) {
                    // Instant verification is applied and a credential is directly returned.
                    // ...
                }

                // [START_EXCLUDE]
                @Override
                public void onVerificationFailed(FirebaseException e) {

                }
                // [END_EXCLUDE]
            });
    // [END auth_test_phone_auto]
}
 
Example #27
Source File: MultiFactorEnrollActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void onClickSignInWithPhoneNumber() {
    String smsCode = mBinding.fieldVerificationCode.getText().toString();
    if (TextUtils.isEmpty(smsCode)) {
        return;
    }
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mCodeVerificationId, smsCode);
    enrollWithPhoneAuthCredential(credential);
}
 
Example #28
Source File: PhoneProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignIn_autoUpgradeAnonymousEnabledWithExistingUser_expectMergeFailure() {
    mHandler.getOperation().observeForever(mResponseObserver);
    setupAnonymousUpgrade();

    FirebaseAuthUserCollisionException ex =
            new FirebaseAuthUserCollisionException("foo", "bar");
    TestHelper.setPrivateField(ex, FirebaseAuthUserCollisionException.class,
            AuthCredential.class, mCredential);

    when(mMockAuth.getCurrentUser().linkWithCredential(mCredential))
            .thenReturn(AutoCompleteTask.<AuthResult>forFailure(ex));

    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            PhoneAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .build();

    mHandler.startSignIn(mCredential, response);

    verify(mMockAuth.getCurrentUser()).linkWithCredential(mCredential);

    InOrder inOrder = inOrder(mResponseObserver);
    inOrder.verify(mResponseObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));

    ArgumentCaptor<Resource<IdpResponse>> resolveCaptor =
            ArgumentCaptor.forClass(Resource.class);
    inOrder.verify(mResponseObserver).onChanged(resolveCaptor.capture());

    FirebaseAuthAnonymousUpgradeException e =
            (FirebaseAuthAnonymousUpgradeException) resolveCaptor.getValue().getException();

    assertThat(e.getResponse().getCredentialForLinking()).isNotNull();
}
 
Example #29
Source File: PhoneAuthActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
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
}
 
Example #30
Source File: PhoneAuthActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
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;
}