com.google.firebase.auth.EmailAuthProvider Java Examples

The following examples show how to use com.google.firebase.auth.EmailAuthProvider. 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: MainActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void reauthenticate() {
    // [START reauthenticate]
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    // Get auth credentials from the user for re-authentication. The example below shows
    // email and password credentials but there are multiple possible providers,
    // such as GoogleAuthProvider or FacebookAuthProvider.
    AuthCredential credential = EmailAuthProvider
            .getCredential("[email protected]", "password1234");

    // Prompt the user to re-provide their sign-in credentials
    user.reauthenticate(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Log.d(TAG, "User re-authenticated.");
                }
            });
    // [END reauthenticate]
}
 
Example #2
Source File: AuthMethodPickerActivityTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomAuthMethodPickerLayoutWithEmailLink() {
    List<String> providers = Arrays.asList(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD);

    AuthMethodPickerLayout customLayout = new AuthMethodPickerLayout
            .Builder(R.layout.fui_provider_button_email)
            .setEmailButtonId(R.id.email_button)
            .build();

    AuthMethodPickerActivity authMethodPickerActivity = createActivityWithCustomLayout(providers, customLayout);

    Button emailButton = authMethodPickerActivity.findViewById(R.id.email_button);
    emailButton.performClick();

    //Expected result -> Directing users to EmailActivity
    ShadowActivity.IntentForResult nextIntent =
            Shadows.shadowOf(authMethodPickerActivity).getNextStartedActivityForResult();
    assertEquals(
            EmailActivity.class.getName(),
            nextIntent.intent.getComponent().getClassName());
}
 
Example #3
Source File: MainActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void reauthWithLink(String email, String emailLink) {
    FirebaseAuth auth = FirebaseAuth.getInstance();

    // [START auth_reauth_with_link]
    // Construct the email link credential from the current URL.
    AuthCredential credential =
            EmailAuthProvider.getCredentialWithLink(email, emailLink);

    // Re-authenticate the user with this credential.
    auth.getCurrentUser().reauthenticateAndRetrieveData(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // User is now successfully reauthenticated
                    } else {
                        Log.e(TAG, "Error reauthenticating", task.getException());
                    }
                }
            });
    // [END auth_reauth_with_link]
}
 
Example #4
Source File: MainActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void differentiateLink(String email) {
    FirebaseAuth auth = FirebaseAuth.getInstance();

    // [START auth_differentiate_link]
    auth.fetchSignInMethodsForEmail(email)
            .addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
                @Override
                public void onComplete(@NonNull Task<SignInMethodQueryResult> task) {
                    if (task.isSuccessful()) {
                        SignInMethodQueryResult result = task.getResult();
                        List<String> signInMethods = result.getSignInMethods();
                        if (signInMethods.contains(EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD)) {
                            // User can sign in with email/password
                        } else if (signInMethods.contains(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD)) {
                            // User can sign in with email/link
                        }
                    } else {
                        Log.e(TAG, "Error getting sign in methods for user", task.getException());
                    }
                }
            });
    // [END auth_differentiate_link]
}
 
Example #5
Source File: AuthMethodPickerActivityTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomAuthMethodPickerLayout() {
    List<String> providers = Arrays.asList(EmailAuthProvider.PROVIDER_ID);

    AuthMethodPickerLayout customLayout = new AuthMethodPickerLayout
            .Builder(R.layout.fui_provider_button_email)
            .setEmailButtonId(R.id.email_button)
            .build();

    AuthMethodPickerActivity authMethodPickerActivity = createActivityWithCustomLayout(providers, customLayout);

    Button emailButton = authMethodPickerActivity.findViewById(R.id.email_button);
    emailButton.performClick();

    //Expected result -> Directing users to EmailActivity
    ShadowActivity.IntentForResult nextIntent =
            Shadows.shadowOf(authMethodPickerActivity).getNextStartedActivityForResult();
    assertEquals(
            EmailActivity.class.getName(),
            nextIntent.intent.getComponent().getClassName());
}
 
Example #6
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 #7
Source File: RegisterEmailFragment.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void validateAndRegisterUser() {
    String email = mEmailEditText.getText().toString();
    String password = mPasswordEditText.getText().toString();
    String name = mNameEditText.getText().toString();

    boolean emailValid = mEmailFieldValidator.validate(email);
    boolean passwordValid = mPasswordFieldValidator.validate(password);
    boolean nameValid = mNameValidator.validate(name);
    if (emailValid && passwordValid && nameValid) {
        mHandler.startSignIn(new IdpResponse.Builder(
                        new User.Builder(EmailAuthProvider.PROVIDER_ID, email)
                                .setName(name)
                                .setPhotoUri(mUser.getPhotoUri())
                                .build())
                        .build(),
                password);
    }
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: AuthMethodPickerActivity.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
private String providerOrEmailLinkProvider(@NonNull String providerId) {
    if (providerId.equals(EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD)) {
        return EmailAuthProvider.PROVIDER_ID;
    }

    return providerId;
}
 
Example #13
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 #14
Source File: AuthOperationManager.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public Task<AuthResult> createOrLinkUserWithEmailAndPassword(@NonNull FirebaseAuth auth,
                                                             @NonNull FlowParameters flowParameters,
                                                             @NonNull String email,
                                                             @NonNull String password) {
    if (canUpgradeAnonymous(auth, flowParameters)) {
        AuthCredential credential = EmailAuthProvider.getCredential(email, password);
        return auth.getCurrentUser().linkWithCredential(credential);
    } else {
        return auth.createUserWithEmailAndPassword(email, password);
    }
}
 
Example #15
Source File: WelcomeBackPasswordHandlerTest.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 WelcomeBackPasswordHandler((Application) ApplicationProvider.getApplicationContext());

    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            EmailAuthProvider.PROVIDER_ID));
    mHandler.initializeForTesting(testParams, mMockAuth, mMockCredentials, null);
}
 
Example #16
Source File: WelcomeBackPasswordHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignIn_anonymousUserUpgradeEnabledWithEmailFlow_expectValidateCredentialAndMergeFailure() {
    setupAnonymousUpgrade();
    mHandler.getOperation().observeForever(mResponseObserver);

    // Fake user with password provider
    User user = new User.Builder(EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL)
            .build();
    IdpResponse response = new IdpResponse.Builder(user)
            .build();

    // Need to control FirebaseAuth's return values
    AuthOperationManager authOperationManager = AuthOperationManager.getInstance();
    authOperationManager.mScratchAuth = mScratchMockAuth;

    when(mScratchMockAuth.signInWithCredential(any(AuthCredential.class)))
            .thenReturn(AutoCompleteTask.forSuccess(FakeAuthResult.INSTANCE));

    // Kick off the sign in flow
    mHandler.startSignIn(TestConstants.EMAIL, TestConstants.PASSWORD, response, null);

    // Verify that signInWithCredential was called
    ArgumentCaptor<EmailAuthCredential> credentialCaptor
            = ArgumentCaptor.forClass(EmailAuthCredential.class);
    verify(mScratchMockAuth).signInWithCredential(credentialCaptor.capture());

    EmailAuthCredential capturedCredential = credentialCaptor.getValue();

    // TODO: EmailAuthCredential no longer exposes .getEmail() or .getPassword()
    // assertThat(capturedCredential.getEmail()).isEqualTo(TestConstants.EMAIL);
    // assertThat(capturedCredential.getPassword()).isEqualTo(TestConstants.PASSWORD);

    verifyMergeFailure();
}
 
Example #17
Source File: WelcomeBackPasswordHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void setupAnonymousUpgrade() {
    // enableAnonymousUpgrade must be set to true
    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            EmailAuthProvider.PROVIDER_ID), /* enableAnonymousUpgrade */ true);
    mHandler.initializeForTesting(testParams, mMockAuth, mMockCredentials, null);

    // Mock isAnonymous() to return true so canUpgradeAnonymous will return true
    when(mUser.isAnonymous()).thenReturn(true);
    when(mMockAuth.getCurrentUser()).thenReturn(mUser);
}
 
Example #18
Source File: SmartLockHandlerTest.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 SmartLockHandler((Application) ApplicationProvider.getApplicationContext());

    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            EmailAuthProvider.PROVIDER_ID));

    mHandler.initializeForTesting(testParams, mMockAuth, mMockCredentials, null);
    mHandler.setResponse(new IdpResponse.Builder(
            new User.Builder(EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build()
    ).build());
}
 
Example #19
Source File: SocialProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testSignInNonIdp_failure() {
    mHandler.getOperation().observeForever(mResultObserver);

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

    mHandler.startSignIn(response);
}
 
Example #20
Source File: RecoverPasswordHandlerTest.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 RecoverPasswordHandler((Application) ApplicationProvider.getApplicationContext());

    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            EmailAuthProvider.PROVIDER_ID));
    mHandler.initializeForTesting(testParams, mMockAuth, null, null);
}
 
Example #21
Source File: EmailLinkSignInHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void setupAnonymousUpgrade() {
    // enableAnonymousUpgrade must be set to true
    FlowParameters testParams = TestHelper.getFlowParameters(Collections.singletonList(
            EmailAuthProvider.PROVIDER_ID), /* enableAnonymousUpgrade */ true);

    testParams.emailLink = mHandler.getArguments().emailLink;
    mHandler.initializeForTesting(testParams, mMockAuth, null, null);

    // Mock isAnonymous() to return true so canUpgradeAnonymous will return true
    when(mMockAnonUser.isAnonymous()).thenReturn(true);
    when(mMockAuth.getCurrentUser()).thenReturn(mMockAnonUser);
}
 
Example #22
Source File: AuthUITest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateStartIntent_shouldHaveEmailAsDefaultProvider() {
    FlowParameters flowParameters = mAuthUi
            .createSignInIntentBuilder()
            .build()
            .getParcelableExtra(ExtraConstants.FLOW_PARAMS);
    assertEquals(1, flowParameters.providers.size());
    assertEquals(EmailAuthProvider.PROVIDER_ID,
            flowParameters.providers.get(0).getProviderId());
}
 
Example #23
Source File: EmailActivityTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignUpButton_validatesFields() {

    EmailActivity emailActivity = createActivity(EmailAuthProvider.PROVIDER_ID);

    // Trigger RegisterEmailFragment (bypass check email)
    emailActivity.onNewUser(
            new User.Builder(EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build());

    Button button = emailActivity.findViewById(R.id.button_create);
    button.performClick();

    TextInputLayout nameLayout = emailActivity.findViewById(R.id.name_layout);
    TextInputLayout passwordLayout = emailActivity.findViewById(R.id.password_layout);

    assertEquals(
            emailActivity.getString(R.string.fui_missing_first_and_last_name),
            nameLayout.getError().toString());
    assertEquals(
            String.format(
                    emailActivity.getResources().getQuantityString(
                            R.plurals.fui_error_weak_password,
                            R.integer.fui_min_password_length),
                    emailActivity.getResources()
                            .getInteger(R.integer.fui_min_password_length)
            ),
            passwordLayout.getError().toString());
}
 
Example #24
Source File: WelcomeBackPasswordPromptTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private WelcomeBackPasswordPrompt createActivity() {
    Intent startIntent = WelcomeBackPasswordPrompt.createIntent(
            ApplicationProvider.getApplicationContext(),
            TestHelper.getFlowParameters(Collections.singletonList(EmailAuthProvider.PROVIDER_ID)),
            new IdpResponse.Builder(new User.Builder(
                    EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL
            ).build()).build());
    return Robolectric
            .buildActivity(WelcomeBackPasswordPrompt.class, startIntent)
            .create()
            .visible()
            .get();
}
 
Example #25
Source File: AuthMethodPickerActivityTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmailLoginFlow() {
    List<String> providers = Arrays.asList(EmailAuthProvider.PROVIDER_ID);

    AuthMethodPickerActivity authMethodPickerActivity = createActivity(providers);

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

    assertEquals(
            EmailActivity.class.getName(),
            nextIntent.intent.getComponent().getClassName());
}
 
Example #26
Source File: RegisterEmailFragment.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    outState.putParcelable(ExtraConstants.USER,
            new User.Builder(EmailAuthProvider.PROVIDER_ID, mEmailEditText.getText().toString())
                    .setName(mNameEditText.getText().toString())
                    .setPhotoUri(mUser.getPhotoUri())
                    .build());
}
 
Example #27
Source File: EmailActivity.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onClickResendEmail(String email) {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        // We're assuming that to get to the TroubleSigningInFragment, we went through
        // the EmailLinkFragment, which was added to the fragment back stack.
        // From here, we're going to register the EmailLinkFragment again, meaning we'd have to
        // pop off the back stack twice to return to the nascar screen. To avoid this,
        // we pre-emptively pop off the last EmailLinkFragment here.
        getSupportFragmentManager().popBackStack();
    }
    AuthUI.IdpConfig emailConfig = ProviderUtils.getConfigFromIdpsOrThrow(
            getFlowParams().providers, EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD);
    showRegisterEmailLinkFragment(
            emailConfig, email);
}
 
Example #28
Source File: EmailActivity.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onNewUser(User user) {
    // New user, direct them to create an account with email/password
    // if account creation is enabled in SignInIntentBuilder

    TextInputLayout emailLayout = findViewById(R.id.email_layout);
    AuthUI.IdpConfig emailConfig = ProviderUtils.getConfigFromIdps(getFlowParams().providers,
            EmailAuthProvider.PROVIDER_ID);

    if (emailConfig == null) {
        emailConfig = ProviderUtils.getConfigFromIdps(getFlowParams().providers,
                EMAIL_LINK_PROVIDER);
    }

    if (emailConfig.getParams().getBoolean(ExtraConstants.ALLOW_NEW_EMAILS, true)) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (emailConfig.getProviderId().equals(EMAIL_LINK_PROVIDER)) {
            showRegisterEmailLinkFragment(emailConfig, user.getEmail());
        } else {
            RegisterEmailFragment fragment = RegisterEmailFragment.newInstance(user);
            ft.replace(R.id.fragment_register_email, fragment, RegisterEmailFragment.TAG);
            if (emailLayout != null) {
                String emailFieldName = getString(R.string.fui_email_field_name);
                ViewCompat.setTransitionName(emailLayout, emailFieldName);
                ft.addSharedElement(emailLayout, emailFieldName);
            }
            ft.disallowAddToBackStack().commit();
        }
    } else {
        emailLayout.setError(getString(R.string.fui_error_email_does_not_exist));
    }
}
 
Example #29
Source File: MainActivity.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public void linkWithSignInLink(String email, String emailLink) {
    FirebaseAuth auth = FirebaseAuth.getInstance();
    
    // [START auth_link_with_link]
    // Construct the email link credential from the current URL.
    AuthCredential credential =
            EmailAuthProvider.getCredentialWithLink(email, emailLink);

    // Link the credential to the current user.
    auth.getCurrentUser().linkWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "Successfully linked emailLink credential!");
                        AuthResult result = task.getResult();
                        // You can access the new user via result.getUser()
                        // Additional user info profile *not* available via:
                        // result.getAdditionalUserInfo().getProfile() == null
                        // You can check if the user is new or existing:
                        // result.getAdditionalUserInfo().isNewUser()
                    } else {
                        Log.e(TAG, "Error linking emailLink credential", task.getException());
                    }
                }
            });
    // [END auth_link_with_link]
}
 
Example #30
Source File: SignInKickstarter.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void handleCredential(final Credential credential) {
    String id = credential.getId();
    String password = credential.getPassword();
    if (TextUtils.isEmpty(password)) {
        String identity = credential.getAccountType();
        if (identity == null) {
            startAuthMethodChoice();
        } else {
            redirectSignIn(
                    ProviderUtils.accountTypeToProviderId(credential.getAccountType()), id);
        }
    } else {
        final IdpResponse response = new IdpResponse.Builder(
                new User.Builder(EmailAuthProvider.PROVIDER_ID, id).build()).build();

        setResult(Resource.<IdpResponse>forLoading());
        getAuth().signInWithEmailAndPassword(id, password)
                .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 FirebaseAuthInvalidUserException
                                || e instanceof FirebaseAuthInvalidCredentialsException) {
                            // In this case the credential saved in SmartLock was not
                            // a valid credential, we should delete it from SmartLock
                            // before continuing.
                            GoogleApiUtils.getCredentialsClient(getApplication())
                                    .delete(credential);
                        }
                        startAuthMethodChoice();
                    }
                });
    }
}