Search in sources :

Example 1 with FirebaseAuthAnonymousUpgradeException

use of com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException in project FirebaseUI-Android by firebase.

the class AuthMethodPickerActivity method handleSignInOperation.

private void handleSignInOperation(final IdpConfig idpConfig, View view) {
    ViewModelProvider supplier = new ViewModelProvider(this);
    final String providerId = idpConfig.getProviderId();
    final ProviderSignInBase<?> provider;
    AuthUI authUI = getAuthUI();
    switch(providerId) {
        case EMAIL_LINK_PROVIDER:
        case EmailAuthProvider.PROVIDER_ID:
            provider = supplier.get(EmailSignInHandler.class).initWith(null);
            break;
        case PhoneAuthProvider.PROVIDER_ID:
            provider = supplier.get(PhoneSignInHandler.class).initWith(idpConfig);
            break;
        case AuthUI.ANONYMOUS_PROVIDER:
            provider = supplier.get(AnonymousSignInHandler.class).initWith(getFlowParams());
            break;
        case GoogleAuthProvider.PROVIDER_ID:
            if (authUI.isUseEmulator()) {
                provider = supplier.get(GenericIdpSignInHandler.class).initWith(GenericIdpSignInHandler.getGenericGoogleConfig());
            } else {
                provider = supplier.get(GoogleSignInHandler.class).initWith(new GoogleSignInHandler.Params(idpConfig));
            }
            break;
        case FacebookAuthProvider.PROVIDER_ID:
            if (authUI.isUseEmulator()) {
                provider = supplier.get(GenericIdpSignInHandler.class).initWith(GenericIdpSignInHandler.getGenericFacebookConfig());
            } else {
                provider = supplier.get(FacebookSignInHandler.class).initWith(idpConfig);
            }
            break;
        default:
            if (!TextUtils.isEmpty(idpConfig.getParams().getString(GENERIC_OAUTH_PROVIDER_ID))) {
                provider = supplier.get(GenericIdpSignInHandler.class).initWith(idpConfig);
                break;
            }
            throw new IllegalStateException("Unknown provider: " + providerId);
    }
    mProviders.add(provider);
    provider.getOperation().observe(this, new ResourceObserver<IdpResponse>(this) {

        @Override
        protected void onSuccess(@NonNull IdpResponse response) {
            handleResponse(response);
        }

        @Override
        protected void onFailure(@NonNull Exception e) {
            if (e instanceof FirebaseAuthAnonymousUpgradeException) {
                finish(RESULT_CANCELED, new Intent().putExtra(ExtraConstants.IDP_RESPONSE, IdpResponse.from(e)));
                return;
            }
            handleResponse(IdpResponse.from(e));
        }

        private void handleResponse(@NonNull IdpResponse response) {
            // If we're using the emulator then the social flows actually use Generic IDP
            // instead which means we shouldn't use the social response handler.
            boolean isSocialResponse = AuthUI.SOCIAL_PROVIDERS.contains(providerId) && !getAuthUI().isUseEmulator();
            if (!response.isSuccessful()) {
                // We have no idea what provider this error stemmed from so just forward
                // this along to the handler.
                mHandler.startSignIn(response);
            } else if (isSocialResponse) {
                // Don't use the response's provider since it can be different than the one
                // that launched the sign-in attempt. Ex: the email flow is started, but
                // ends up turning into a Google sign-in because that account already
                // existed. In the previous example, an extra sign-in would incorrectly
                // started.
                mHandler.startSignIn(response);
            } else {
                // Email, phone, or generic: the credentials should have already been saved so
                // simply move along.
                // Anononymous sign in also does not require any other operations.
                finish(response.isSuccessful() ? RESULT_OK : RESULT_CANCELED, response.toIntent());
            }
        }
    });
    view.setOnClickListener(view1 -> {
        if (isOffline()) {
            Snackbar.make(findViewById(android.R.id.content), getString(R.string.fui_no_internet), Snackbar.LENGTH_SHORT).show();
            return;
        }
        provider.startSignIn(getAuth(), AuthMethodPickerActivity.this, idpConfig.getProviderId());
    });
}
Also used : Intent(android.content.Intent) AuthUI(com.firebase.ui.auth.AuthUI) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) UserCancellationException(com.firebase.ui.auth.data.model.UserCancellationException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) ViewModelProvider(androidx.lifecycle.ViewModelProvider) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 2 with FirebaseAuthAnonymousUpgradeException

use of com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException in project FirebaseUI-Android by firebase.

the class SingleSignInActivity method onCreate.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    User user = User.getUser(getIntent());
    final String provider = user.getProviderId();
    AuthUI.IdpConfig providerConfig = ProviderUtils.getConfigFromIdps(getFlowParams().providers, provider);
    if (providerConfig == null) {
        finish(RESULT_CANCELED, IdpResponse.getErrorIntent(new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, "Provider not enabled: " + provider)));
        return;
    }
    ViewModelProvider supplier = new ViewModelProvider(this);
    mHandler = supplier.get(SocialProviderResponseHandler.class);
    mHandler.init(getFlowParams());
    boolean useEmulator = getAuthUI().isUseEmulator();
    switch(provider) {
        case GoogleAuthProvider.PROVIDER_ID:
            if (useEmulator) {
                mProvider = supplier.get(GenericIdpSignInHandler.class).initWith(GenericIdpSignInHandler.getGenericGoogleConfig());
            } else {
                mProvider = supplier.get(GoogleSignInHandler.class).initWith(new GoogleSignInHandler.Params(providerConfig, user.getEmail()));
            }
            break;
        case FacebookAuthProvider.PROVIDER_ID:
            if (useEmulator) {
                mProvider = supplier.get(GenericIdpSignInHandler.class).initWith(GenericIdpSignInHandler.getGenericFacebookConfig());
            } else {
                mProvider = supplier.get(FacebookSignInHandler.class).initWith(providerConfig);
            }
            break;
        default:
            if (!TextUtils.isEmpty(providerConfig.getParams().getString(GENERIC_OAUTH_PROVIDER_ID))) {
                mProvider = supplier.get(GenericIdpSignInHandler.class).initWith(providerConfig);
                break;
            }
            throw new IllegalStateException("Invalid provider id: " + provider);
    }
    mProvider.getOperation().observe(this, new ResourceObserver<IdpResponse>(this) {

        @Override
        protected void onSuccess(@NonNull IdpResponse response) {
            boolean useSocialHandler = AuthUI.SOCIAL_PROVIDERS.contains(provider) && !getAuthUI().isUseEmulator();
            if (useSocialHandler || !response.isSuccessful()) {
                mHandler.startSignIn(response);
                return;
            }
            finish(response.isSuccessful() ? RESULT_OK : RESULT_CANCELED, response.toIntent());
        }

        @Override
        protected void onFailure(@NonNull Exception e) {
            if (e instanceof FirebaseAuthAnonymousUpgradeException) {
                finish(RESULT_CANCELED, new Intent().putExtra(ExtraConstants.IDP_RESPONSE, IdpResponse.from(e)));
                return;
            }
            mHandler.startSignIn(IdpResponse.from(e));
        }
    });
    mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>(this) {

        @Override
        protected void onSuccess(@NonNull IdpResponse response) {
            startSaveCredentials(mHandler.getCurrentUser(), response, null);
        }

        @Override
        protected void onFailure(@NonNull Exception e) {
            if (e instanceof FirebaseAuthAnonymousUpgradeException) {
                IdpResponse res = ((FirebaseAuthAnonymousUpgradeException) e).getResponse();
                finish(RESULT_CANCELED, new Intent().putExtra(ExtraConstants.IDP_RESPONSE, res));
            } else {
                finish(RESULT_CANCELED, IdpResponse.getErrorIntent(e));
            }
        }
    });
    if (mHandler.getOperation().getValue() == null) {
        mProvider.startSignIn(getAuth(), this, provider);
    }
}
Also used : User(com.firebase.ui.auth.data.model.User) Intent(android.content.Intent) AuthUI(com.firebase.ui.auth.AuthUI) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) SocialProviderResponseHandler(com.firebase.ui.auth.viewmodel.idp.SocialProviderResponseHandler) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) ViewModelProvider(androidx.lifecycle.ViewModelProvider) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 3 with FirebaseAuthAnonymousUpgradeException

use of com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException in project FirebaseUI-Android by firebase.

the class PhoneActivity method handleError.

private void handleError(@Nullable Exception e) {
    TextInputLayout errorView = getErrorView();
    if (errorView == null) {
        return;
    }
    if (e instanceof FirebaseAuthAnonymousUpgradeException) {
        IdpResponse response = ((FirebaseAuthAnonymousUpgradeException) e).getResponse();
        finish(ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT, response.toIntent());
    } else if (e instanceof FirebaseAuthException) {
        FirebaseAuthError error = FirebaseAuthError.fromException((FirebaseAuthException) e);
        if (error == FirebaseAuthError.ERROR_USER_DISABLED) {
            IdpResponse response = IdpResponse.from(new FirebaseUiException(ErrorCodes.ERROR_USER_DISABLED));
            finish(RESULT_CANCELED, response.toIntent());
            return;
        }
        errorView.setError(getErrorMessage(error));
    } else if (e != null) {
        errorView.setError(getErrorMessage(FirebaseAuthError.ERROR_UNKNOWN));
    } else {
        errorView.setError(null);
    }
}
Also used : FirebaseAuthError(com.firebase.ui.auth.util.FirebaseAuthError) TextInputLayout(com.google.android.material.textfield.TextInputLayout) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseAuthException(com.google.firebase.auth.FirebaseAuthException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 4 with FirebaseAuthAnonymousUpgradeException

use of com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException in project FirebaseUI-Android by firebase.

the class GenericIdpSignInHandlerTest method testStartSignIn_anonymousUpgradeFlowWithConflict_expectRecoverableError.

@Test
public void testStartSignIn_anonymousUpgradeFlowWithConflict_expectRecoverableError() {
    setupAnonymousUpgrade();
    AuthCredential credential = OAuthProvider.newCredentialBuilder(MICROSOFT_PROVIDER).setIdToken(ID_TOKEN).setAccessToken(ACCESS_TOKEN).build();
    FirebaseAuthUserCollisionException collisionException = new FirebaseAuthUserCollisionException("foo", "bar");
    collisionException.zzb(EMAIL).zza(credential);
    when(mMockAuth.getCurrentUser().startActivityForLinkWithProvider(any(Activity.class), any(OAuthProvider.class))).thenReturn(AutoCompleteTask.forFailure(collisionException));
    // Case 1: Anon user signing in with an existing account
    when(mMockAuth.fetchSignInMethodsForEmail(any(String.class))).thenReturn(AutoCompleteTask.forSuccess(new FakeSignInMethodQueryResult(Arrays.asList(MICROSOFT_PROVIDER))));
    mockOAuthProvider(MICROSOFT_PROVIDER);
    mHandler.startSignIn(mMockAuth, mMockActivity, MICROSOFT_PROVIDER);
    ArgumentCaptor<OAuthProvider> providerCaptor = ArgumentCaptor.forClass(OAuthProvider.class);
    verify(mMockAuth.getCurrentUser()).startActivityForLinkWithProvider(eq(mMockActivity), providerCaptor.capture());
    assertThat(providerCaptor.getValue().getProviderId()).isEqualTo(MICROSOFT_PROVIDER);
    InOrder inOrder = inOrder(mResponseObserver);
    inOrder.verify(mResponseObserver).onChanged(argThat(ResourceMatchers.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();
}
Also used : AuthCredential(com.google.firebase.auth.AuthCredential) FakeSignInMethodQueryResult(com.firebase.ui.auth.testhelpers.FakeSignInMethodQueryResult) InOrder(org.mockito.InOrder) Resource(com.firebase.ui.auth.data.model.Resource) Activity(android.app.Activity) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) OAuthProvider(com.google.firebase.auth.OAuthProvider) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) Test(org.junit.Test)

Example 5 with FirebaseAuthAnonymousUpgradeException

use of com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException in project FirebaseUI-Android by firebase.

the class EmailLinkSignInHandlerTest method testStartSignIn_normalFlowWithAnonymousUpgrade_expectMergeFailure.

@Test
@SuppressWarnings("all")
public void testStartSignIn_normalFlowWithAnonymousUpgrade_expectMergeFailure() {
    mHandler.getOperation().observeForever(mResponseObserver);
    setupAnonymousUpgrade();
    when(mMockAuth.isSignInWithEmailLink(any(String.class))).thenReturn(true);
    mPersistenceManager.saveEmail(ApplicationProvider.getApplicationContext(), TestConstants.EMAIL, TestConstants.SESSION_ID, TestConstants.UID);
    when(mMockAuth.getCurrentUser().linkWithCredential(any(AuthCredential.class))).thenReturn(AutoCompleteTask.<AuthResult>forFailure(new FirebaseAuthUserCollisionException("foo", "bar")));
    mHandler.startSignIn();
    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());
    assertThat(captor.getValue().getException()).isNotNull();
    FirebaseAuthAnonymousUpgradeException mergeException = (FirebaseAuthAnonymousUpgradeException) captor.getValue().getException();
    assertThat(mergeException.getResponse().getCredentialForLinking()).isNotNull();
    assertThat(mPersistenceManager.retrieveSessionRecord(ApplicationProvider.getApplicationContext())).isNull();
}
Also used : FacebookAuthCredential(com.google.firebase.auth.FacebookAuthCredential) EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) InOrder(org.mockito.InOrder) Resource(com.firebase.ui.auth.data.model.Resource) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) IdpResponse(com.firebase.ui.auth.IdpResponse) Test(org.junit.Test)

Aggregations

FirebaseAuthAnonymousUpgradeException (com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException)16 IdpResponse (com.firebase.ui.auth.IdpResponse)14 Resource (com.firebase.ui.auth.data.model.Resource)8 InOrder (org.mockito.InOrder)8 FirebaseUiException (com.firebase.ui.auth.FirebaseUiException)7 Test (org.junit.Test)7 ViewModelProvider (androidx.lifecycle.ViewModelProvider)6 AuthCredential (com.google.firebase.auth.AuthCredential)6 FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)4 Intent (android.content.Intent)3 TextView (android.widget.TextView)3 AuthUI (com.firebase.ui.auth.AuthUI)3 User (com.firebase.ui.auth.data.model.User)3 UserCancellationException (com.firebase.ui.auth.data.model.UserCancellationException)3 EmailAuthCredential (com.google.firebase.auth.EmailAuthCredential)3 FakeSignInMethodQueryResult (com.firebase.ui.auth.testhelpers.FakeSignInMethodQueryResult)2 FirebaseAuthError (com.firebase.ui.auth.util.FirebaseAuthError)2 SocialProviderResponseHandler (com.firebase.ui.auth.viewmodel.idp.SocialProviderResponseHandler)2 FacebookAuthCredential (com.google.firebase.auth.FacebookAuthCredential)2 FirebaseAuthException (com.google.firebase.auth.FirebaseAuthException)2