com.firebase.ui.auth.IdpResponse Java Examples

The following examples show how to use com.firebase.ui.auth.IdpResponse. 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: GenericIdpSignInHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void startSignIn(@NonNull FirebaseAuth auth,
                        @NonNull HelperActivityBase activity,
                        @NonNull String providerId) {
    setResult(Resource.<IdpResponse>forLoading());

    FlowParameters flowParameters = activity.getFlowParams();
    OAuthProvider provider = buildOAuthProvider(providerId);
    if (flowParameters != null
            && AuthOperationManager.getInstance().canUpgradeAnonymous(auth, flowParameters)) {
        handleAnonymousUpgradeFlow(auth, activity, provider, flowParameters);
        return;
    }

    handleNormalSignInFlow(auth, activity, provider);
}
 
Example #2
Source File: SignedInActivity.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void populateIdpToken(@Nullable IdpResponse response) {
    String token = null;
    String secret = null;
    if (response != null) {
        token = response.getIdpToken();
        secret = response.getIdpSecret();
    }

    View idpTokenLayout = findViewById(R.id.idp_token_layout);
    if (token == null) {
        idpTokenLayout.setVisibility(View.GONE);
    } else {
        idpTokenLayout.setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.idp_token)).setText(token);
    }

    View idpSecretLayout = findViewById(R.id.idp_secret_layout);
    if (secret == null) {
        idpSecretLayout.setVisibility(View.GONE);
    } else {
        idpSecretLayout.setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.idp_secret)).setText(secret);
    }
}
 
Example #3
Source File: EmailLinkSignInHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("all")
public void
testStartSignIn_differentDeviceLinkWithForceSameDeviceTrue_expectWrongDeviceError() {
    String differentSessionId = SessionUtils.generateRandomAlphaNumericString(10);
    initializeHandlerWithSessionInfo(differentSessionId, null, null, true);

    mHandler.getOperation().observeForever(mResponseObserver);
    when(mMockAuth.isSignInWithEmailLink(any(String.class))).thenReturn(true);


    mHandler.startSignIn();

    verify(mMockAuth).isSignInWithEmailLink(any(String.class));
    ArgumentCaptor<Resource<IdpResponse>> captor =
            ArgumentCaptor.forClass(Resource.class);

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

    FirebaseUiException exception = (FirebaseUiException) captor.getValue().getException();
    assertThat(exception).isNotNull();
    assertThat(exception.getErrorCode()).isEqualTo(ErrorCodes.EMAIL_LINK_WRONG_DEVICE_ERROR);
}
 
Example #4
Source File: FirebaseUIActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        IdpResponse response = IdpResponse.fromResultIntent(data);

        if (resultCode == RESULT_OK) {
            // Successfully signed in
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            // ...
        } else {
            // Sign in failed. If response is null the user canceled the
            // sign-in flow using the back button. Otherwise check
            // response.getError().getErrorCode() and handle the error.
            // ...
        }
    }
}
 
Example #5
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        mViewModel.setIsSigningIn(false);

        if (resultCode != RESULT_OK) {
            if (response == null) {
                // User pressed the back button.
                finish();
            } else if (response.getError() != null
                    && response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) {
                showSignInErrorDialog(R.string.message_no_network);
            } else {
                showSignInErrorDialog(R.string.message_unknown);
            }
        }
    }
}
 
Example #6
Source File: EmailLinkFragment.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    initHandler();

    String email = getArguments().getString(ExtraConstants.EMAIL);
    ActionCodeSettings actionCodeSettings
            = getArguments().getParcelable(ExtraConstants.ACTION_CODE_SETTINGS);
    IdpResponse idpResponseForLinking
            = getArguments().getParcelable(ExtraConstants.IDP_RESPONSE);
    boolean forceSameDevice
            = getArguments().getBoolean(ExtraConstants.FORCE_SAME_DEVICE);

    if (!mEmailSent) {
        mEmailLinkSendEmailHandler.sendSignInLinkToEmail(email, actionCodeSettings,
                idpResponseForLinking, forceSameDevice);
    }
}
 
Example #7
Source File: BaseAuthActivity.java    From q-municate-android with Apache License 2.0 6 votes vote down vote up
private void onReceiveFirebaseAuthResult(int resultCode, Intent data) {
        IdpResponse response = IdpResponse.fromResultIntent(data);

        // Successfully signed in
        if (resultCode == RESULT_OK) {
            firebaseAuthHelper.refreshInternalFirebaseToken(firebaseAuthCallback);
        } else {
             //Sign in failed
            if (response == null) {
                // User pressed back button
                Log.i(TAG, "BACK button pressed");
                return;
            }

            if (response.getErrorCode() == ErrorCodes.NO_NETWORK || response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
                showSnackbar(R.string.dlg_internet_connection_error, Snackbar.LENGTH_INDEFINITE);
            }
        }
}
 
Example #8
Source File: AnonymousUpgradeActivity.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anonymous_upgrade);
    ButterKnife.bind(this);

    updateUI();

    // Got here from AuthUIActivity, and we need to deal with a merge conflict
    // Occurs after catching an email link
    IdpResponse response = IdpResponse.fromResultIntent(getIntent());
    if (response != null) {
        handleSignInResult(RC_SIGN_IN, ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT,
                getIntent());
    }
}
 
Example #9
Source File: AnonymousUpgradeActivity.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void handleSignInResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RC_SIGN_IN) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        if (response == null) {
            // User pressed back button
            return;
        }
        if (resultCode == RESULT_OK) {
            setStatus("Signed in as " + getUserIdentifier(FirebaseAuth.getInstance()
                    .getCurrentUser()));
        } else if (response.getError().getErrorCode() == ErrorCodes
                .ANONYMOUS_UPGRADE_MERGE_CONFLICT) {
            setStatus("Merge conflict: user already exists.");
            mResolveMergeButton.setEnabled(true);
            mPendingCredential = response.getCredentialForLinking();
        } else {
            Toast.makeText(this, "Auth error, see logs", Toast.LENGTH_SHORT).show();
            Log.w(TAG, "Error: " + response.getError().getMessage(), response.getError());
        }

        updateUI();
    }
}
 
Example #10
Source File: SocialProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignInIdp_anonymousUserUpgradeEnabledAndNewUser_expectSuccess() {
    mHandler.getOperation().observeForever(mResultObserver);
    setupAnonymousUpgrade();

    when(mMockAuth.getCurrentUser().linkWithCredential(any(AuthCredential.class)))
            .thenReturn(AutoCompleteTask.forSuccess(FakeAuthResult.INSTANCE));

    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .setToken(TestConstants.TOKEN)
            .build();

    mHandler.startSignIn(response);

    verify(mMockAuth.getCurrentUser()).linkWithCredential(any(AuthCredential.class));

    InOrder inOrder = inOrder(mResultObserver);
    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));
    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #11
Source File: EmailLinkSendEmailHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private ActionCodeSettings addSessionInfoToActionCodeSettings(@NonNull ActionCodeSettings
                                                                      actionCodeSettings,
                                                              @NonNull String sessionId,
                                                              @NonNull String anonymousUserId,
                                                              @Nullable IdpResponse response,
                                                              boolean forceSameDevice) {

    String continueUrl = actionCodeSettings.getUrl();
    ContinueUrlBuilder continueUrlBuilder = new ContinueUrlBuilder(continueUrl);
    continueUrlBuilder.appendSessionId(sessionId);
    continueUrlBuilder.appendAnonymousUserId(anonymousUserId);
    continueUrlBuilder.appendForceSameDeviceBit(forceSameDevice);
    if (response != null) {
        continueUrlBuilder.appendProviderId(response.getProviderType());
    }

    return ActionCodeSettings.newBuilder()
            .setUrl(continueUrlBuilder.build())
            .setHandleCodeInApp(true)
            .setAndroidPackageName(actionCodeSettings.getAndroidPackageName(),
                    actionCodeSettings.getAndroidInstallApp(),
                    actionCodeSettings.getAndroidMinimumVersion())
            .setIOSBundleId(actionCodeSettings.getIOSBundle())
            .build();
}
 
Example #12
Source File: EmailLinkPromptEmailFragment.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void initHandler() {
    mHandler = ViewModelProviders.of(this).get(EmailLinkSignInHandler.class);
    mHandler.init(getFlowParams());
    mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>(this) {
        @Override
        protected void onSuccess(@NonNull IdpResponse response) {
            mListener.onEmailPromptSuccess(response);
        }

        @Override
        protected void onFailure(@NonNull final Exception e) {
            // We've checked the oob code before starting this flow via #checkActionCode.
            // I don't see this failing in a non-recoverable way.
            mEmailLayout.setError(e.getMessage());
        }
    });
}
 
Example #13
Source File: EmailLinkSignInHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void finishSignIn(@NonNull String email, @Nullable IdpResponse response) {
    if (TextUtils.isEmpty(email)) {
        setResult(Resource.<IdpResponse>forFailure(
                new FirebaseUiException(ErrorCodes.EMAIL_MISMATCH_ERROR)));
        return;
    }
    final AuthOperationManager authOperationManager = AuthOperationManager.getInstance();
    final EmailLinkPersistenceManager persistenceManager = EmailLinkPersistenceManager
            .getInstance();
    String link = getArguments().emailLink;
    if (response == null) {
        handleNormalFlow(authOperationManager, persistenceManager, email, link);
    } else {
        handleLinkingFlow(authOperationManager, persistenceManager, response, link);
    }
}
 
Example #14
Source File: EmailLinkPersistanceManagerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaveAndRetrieveIdpResonseForLinking_saveEmailFirst() {
    IdpResponse response = buildIdpResponse();

    mPersistenceManager.saveEmail(
            ApplicationProvider.getApplicationContext(),
            TestConstants.EMAIL, TestConstants.SESSION_ID, TestConstants.UID);
    mPersistenceManager.saveIdpResponseForLinking(
            ApplicationProvider.getApplicationContext(), response);

    SessionRecord sessionRecord = mPersistenceManager
            .retrieveSessionRecord(ApplicationProvider.getApplicationContext());

    assertThat(sessionRecord.getEmail()).isEqualTo(TestConstants.EMAIL);
    assertThat(sessionRecord.getSessionId()).isEqualTo(TestConstants.SESSION_ID);
    assertThat(sessionRecord.getAnonymousUserId()).isEqualTo(TestConstants.UID);
    assertThat(sessionRecord.getIdpResponseForLinking()).isEqualTo(response);
}
 
Example #15
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 #16
Source File: EmailLinkSignInHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("all")
public void
testStartSignIn_differentDeviceLinkWithNoSessionId_expectInvalidLinkError() {
    initializeHandlerWithSessionInfo(null, null, null, true);

    mHandler.getOperation().observeForever(mResponseObserver);
    when(mMockAuth.isSignInWithEmailLink(any(String.class))).thenReturn(true);

    mHandler.startSignIn();

    verify(mMockAuth).isSignInWithEmailLink(any(String.class));
    ArgumentCaptor<Resource<IdpResponse>> captor =
            ArgumentCaptor.forClass(Resource.class);

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

    FirebaseUiException exception = (FirebaseUiException) captor.getValue().getException();
    assertThat(exception).isNotNull();
    assertThat(exception.getErrorCode()).isEqualTo(ErrorCodes.INVALID_EMAIL_LINK_ERROR);
}
 
Example #17
Source File: SocialProviderResponseHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == RequestCodes.ACCOUNT_LINK_FLOW) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        if (resultCode == Activity.RESULT_OK) {
            setResult(Resource.forSuccess(response));
        } else {
            Exception e;
            if (response == null) {
                e = new FirebaseUiException(
                        ErrorCodes.UNKNOWN_ERROR, "Link canceled by user.");
            } else {
                e = response.getError();
            }
            setResult(Resource.<IdpResponse>forFailure(e));
        }
    }
}
 
Example #18
Source File: SocialProviderResponseHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void handleGenericIdpLinkingFlow(@NonNull final IdpResponse idpResponse) {
    ProviderUtils.fetchSortedProviders(getAuth(), getArguments(), idpResponse.getEmail())
            .addOnSuccessListener(new OnSuccessListener<List<String>>() {
                @Override
                public void onSuccess(@NonNull List<String> providers) {
                    if (providers.isEmpty()) {
                        setResult(Resource.<IdpResponse>forFailure(
                                new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR,
                                        "No supported providers.")));
                        return;
                    }
                    startWelcomeBackFlowForLinking(providers.get(0), idpResponse);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    setResult(Resource.<IdpResponse>forFailure(e));
                }
            });
}
 
Example #19
Source File: GenericIdpAnonymousUpgradeLinkingHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void startSignIn(@NonNull FirebaseAuth auth,
                        @NonNull HelperActivityBase activity,
                        @NonNull String providerId) {
    setResult(Resource.<IdpResponse>forLoading());

    FlowParameters flowParameters = activity.getFlowParams();
    OAuthProvider provider = buildOAuthProvider(providerId);
    if (flowParameters != null
            && AuthOperationManager.getInstance().canUpgradeAnonymous(auth, flowParameters)) {
            handleAnonymousUpgradeLinkingFlow(activity, provider, flowParameters);
        return;
    }

    handleNormalSignInFlow(auth, activity, provider);
}
 
Example #20
Source File: LinkingSocialProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignIn_withSameIdp_expectSuccess() {
    mHandler.getOperation().observeForever(mResponseObserver);

    // Fake social response from Google
    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .setToken(TestConstants.TOKEN)
            .build();

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

    mHandler.startSignIn(response);

    verify(mMockAuth).signInWithCredential(any(GoogleAuthCredential.class));

    InOrder inOrder = inOrder(mResponseObserver);
    inOrder.verify(mResponseObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));
    inOrder.verify(mResponseObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #21
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 #22
Source File: AnonymousSignInHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void startSignIn(@NonNull HelperActivityBase activity) {
    setResult(Resource.<IdpResponse>forLoading());

    // Calling signInAnonymously() will always return the same anonymous user if already
    // available. This is enforced by the client SDK.
    mAuth.signInAnonymously()
            .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult result) {
                    setResult(Resource.<IdpResponse>forSuccess(initResponse(
                            result.getAdditionalUserInfo().isNewUser())));
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    setResult(Resource.<IdpResponse>forFailure(e));
                }
            });

}
 
Example #23
Source File: WelcomeBackPasswordHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
private void verifyMergeFailure() {
    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());

    EmailAuthCredential responseCredential =
            (EmailAuthCredential) e.getResponse().getCredentialForLinking();

    // TODO: EmailAuthCredential no longer exposes .getEmail() or .getPassword()
    // assertThat(responseCredential.getEmail()).isEqualTo(TestConstants.EMAIL);
    // assertThat(responseCredential.getPassword()).isEqualTo(TestConstants.PASSWORD);
}
 
Example #24
Source File: StartupActivity.java    From Track-My-Location with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_LOGIN) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        if (resultCode == RESULT_OK) {
            goToMainActivity();
        } else {
            if (response == null) {
                Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show();
            } else if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) {
                Toast.makeText(this, "No Network Connection", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
 
Example #25
Source File: GenericIdpSignInHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == RequestCodes.GENERIC_IDP_SIGN_IN_FLOW) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        if (response == null) {
            setResult(Resource.<IdpResponse>forFailure(new UserCancellationException()));
        } else {
            setResult(Resource.forSuccess(response));
        }
    }
}
 
Example #26
Source File: WelcomeBackIdpPrompt.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public static Intent createIntent(
        Context context,
        FlowParameters flowParams,
        User existingUser,
        @Nullable IdpResponse requestedUserResponse) {
    return createBaseIntent(context, WelcomeBackIdpPrompt.class, flowParams)
            .putExtra(ExtraConstants.IDP_RESPONSE, requestedUserResponse)
            .putExtra(ExtraConstants.USER, existingUser);
}
 
Example #27
Source File: GoogleSignInHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private static IdpResponse createIdpResponse(GoogleSignInAccount account) {
    return new IdpResponse.Builder(
            new User.Builder(GoogleAuthProvider.PROVIDER_ID, account.getEmail())
                    .setName(account.getDisplayName())
                    .setPhotoUri(account.getPhotoUrl())
                    .build())
            .setToken(account.getIdToken())
            .build();
}
 
Example #28
Source File: SmartLockHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveCredentials_resolution() {
    mHandler.getOperation().observeForever(mResultObserver);

    // Mock credentials to throw an RAE
    ResolvableApiException mockRae = mock(ResolvableApiException.class);
    when(mMockCredentials.save(any(Credential.class)))
            .thenReturn(AutoCompleteTask.<Void>forFailure(mockRae));

    // Kick off save
    mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null);

    InOrder inOrder = inOrder(mResultObserver);

    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));

    // Make sure we get a resolution
    ArgumentCaptor<Resource<IdpResponse>> resolveCaptor =
            ArgumentCaptor.forClass(Resource.class);
    inOrder.verify(mResultObserver).onChanged(resolveCaptor.capture());

    // Call activity result
    PendingIntentRequiredException e =
            ((PendingIntentRequiredException) resolveCaptor.getValue().getException());
    mHandler.onActivityResult(e.getRequestCode(), Activity.RESULT_OK);

    // Make sure we get success
    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #29
Source File: SocialProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignInIdp_anonymousUserUpgradeEnabledAndExistingUserWithSameIdp_expectMergeFailure() {
    mHandler.getOperation().observeForever(mResultObserver);
    setupAnonymousUpgrade();

    when(mMockAuth.getCurrentUser().linkWithCredential(any(AuthCredential.class)))
            .thenReturn(AutoCompleteTask.<AuthResult>forFailure(
                    new FirebaseAuthUserCollisionException("foo", "bar")));

    // Case 1: Anon user signing in with a Google credential that belongs to an existing user.
    when(mMockAuth.fetchSignInMethodsForEmail(any(String.class)))
            .thenReturn(AutoCompleteTask.<SignInMethodQueryResult>forSuccess(
                    new FakeSignInMethodQueryResult(Arrays.asList(
                            GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
                            FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD))));


    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .setToken(TestConstants.TOKEN)
            .build();

    mHandler.startSignIn(response);

    verify(mMockAuth.getCurrentUser()).linkWithCredential(any(AuthCredential.class));

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

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

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

    assertThat(e.getResponse().getCredentialForLinking()).isNotNull();
}
 
Example #30
Source File: LinkingSocialProviderResponseHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignIn_anonymousUpgradeEnabledWithSameIdp_expectMergeFailure() {
    mHandler.getOperation().observeForever(mResponseObserver);
    setupAnonymousUpgrade();

    // Fake social response from Google
    IdpResponse response = new IdpResponse.Builder(new User.Builder(
            GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build())
            .setToken(TestConstants.TOKEN)
            .build();

    mHandler.startSignIn(response);

    // Since we are signing in with the same IDP and anonymous upgrade is enabled, a merge
    // failure should occur without any RPC calls

    AuthCredential credential = GoogleAuthProvider.getCredential(TestConstants.TOKEN, null);

    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();

    GoogleAuthCredential responseCredential =
            (GoogleAuthCredential) e.getResponse().getCredentialForLinking();

    assertThat(responseCredential.getProvider()).isEqualTo(credential.getProvider());
    assertThat(responseCredential.getSignInMethod()).isEqualTo(credential.getSignInMethod());

}