Search in sources :

Example 1 with User

use of com.firebase.ui.auth.data.model.User in project FirebaseUI-Android by firebase.

the class ProfileMerger method then.

@Override
public Task<AuthResult> then(@NonNull Task<AuthResult> task) {
    final AuthResult authResult = task.getResult();
    FirebaseUser firebaseUser = authResult.getUser();
    String name = firebaseUser.getDisplayName();
    Uri photoUri = firebaseUser.getPhotoUrl();
    if (!TextUtils.isEmpty(name) && photoUri != null) {
        return Tasks.forResult(authResult);
    }
    User user = mResponse.getUser();
    if (TextUtils.isEmpty(name)) {
        name = user.getName();
    }
    if (photoUri == null) {
        photoUri = user.getPhotoUri();
    }
    return firebaseUser.updateProfile(new UserProfileChangeRequest.Builder().setDisplayName(name).setPhotoUri(photoUri).build()).addOnFailureListener(new TaskFailureLogger(TAG, "Error updating profile")).continueWithTask(task1 -> Tasks.forResult(authResult));
}
Also used : User(com.firebase.ui.auth.data.model.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) TaskFailureLogger(com.firebase.ui.auth.util.data.TaskFailureLogger) AuthResult(com.google.firebase.auth.AuthResult) FirebaseUser(com.google.firebase.auth.FirebaseUser) Uri(android.net.Uri)

Example 2 with User

use of com.firebase.ui.auth.data.model.User 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 User

use of com.firebase.ui.auth.data.model.User in project FirebaseUI-Android by firebase.

the class GenericIdpSignInHandler method handleAnonymousUpgradeFlow.

private void handleAnonymousUpgradeFlow(final FirebaseAuth auth, final HelperActivityBase activity, final OAuthProvider provider, final FlowParameters flowParameters) {
    final boolean useEmulator = activity.getAuthUI().isUseEmulator();
    auth.getCurrentUser().startActivityForLinkWithProvider(activity, provider).addOnSuccessListener(authResult -> handleSuccess(useEmulator, provider.getProviderId(), authResult.getUser(), (OAuthCredential) authResult.getCredential(), authResult.getAdditionalUserInfo().isNewUser())).addOnFailureListener(e -> {
        if (!(e instanceof FirebaseAuthUserCollisionException)) {
            setResult(Resource.forFailure(e));
            return;
        }
        FirebaseAuthUserCollisionException collisionException = (FirebaseAuthUserCollisionException) e;
        final AuthCredential credential = collisionException.getUpdatedCredential();
        final String email = collisionException.getEmail();
        // Case 1: Anonymous user trying to link with an existing user
        // Case 2: Anonymous user trying to link with a provider keyed
        // by an email that already belongs to an existing account
        // (linking flow)
        ProviderUtils.fetchSortedProviders(auth, flowParameters, email).addOnSuccessListener(providers -> {
            if (providers.isEmpty()) {
                String errorMessage = "Unable to complete the linkingflow -" + " the user is using " + "unsupported providers.";
                setResult(Resource.forFailure(new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, errorMessage)));
                return;
            }
            if (providers.contains(provider.getProviderId())) {
                // Case 1
                handleMergeFailure(credential);
            } else {
                // Case 2 - linking flow to be handled by
                // SocialProviderResponseHandler
                setResult(Resource.forFailure(new FirebaseUiUserCollisionException(ErrorCodes.ERROR_GENERIC_IDP_RECOVERABLE_ERROR, "Recoverable error.", provider.getProviderId(), email, credential)));
            }
        });
    });
}
Also used : ProviderUtils(com.firebase.ui.auth.util.data.ProviderUtils) NonNull(androidx.annotation.NonNull) User(com.firebase.ui.auth.data.model.User) Intent(android.content.Intent) Resource(com.firebase.ui.auth.data.model.Resource) ExtraConstants(com.firebase.ui.auth.util.ExtraConstants) HashMap(java.util.HashMap) FirebaseUiUserCollisionException(com.firebase.ui.auth.FirebaseUiUserCollisionException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) GoogleAuthProvider(com.google.firebase.auth.GoogleAuthProvider) OAuthCredential(com.google.firebase.auth.OAuthCredential) RestrictTo(androidx.annotation.RestrictTo) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) AuthUI(com.firebase.ui.auth.AuthUI) R(com.firebase.ui.auth.R) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) UserCancellationException(com.firebase.ui.auth.data.model.UserCancellationException) HelperActivityBase(com.firebase.ui.auth.ui.HelperActivityBase) FirebaseUser(com.google.firebase.auth.FirebaseUser) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) FacebookAuthProvider(com.google.firebase.auth.FacebookAuthProvider) FirebaseAuthError(com.firebase.ui.auth.util.FirebaseAuthError) OAuthProvider(com.google.firebase.auth.OAuthProvider) AuthCredential(com.google.firebase.auth.AuthCredential) FlowParameters(com.firebase.ui.auth.data.model.FlowParameters) List(java.util.List) Nullable(androidx.annotation.Nullable) Application(android.app.Application) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) FirebaseAuthException(com.google.firebase.auth.FirebaseAuthException) ProviderSignInBase(com.firebase.ui.auth.viewmodel.ProviderSignInBase) RequestCodes(com.firebase.ui.auth.viewmodel.RequestCodes) AuthResult(com.google.firebase.auth.AuthResult) ErrorCodes(com.firebase.ui.auth.ErrorCodes) VisibleForTesting(androidx.annotation.VisibleForTesting) IdpResponse(com.firebase.ui.auth.IdpResponse) OAuthCredential(com.google.firebase.auth.OAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseUiUserCollisionException(com.firebase.ui.auth.FirebaseUiUserCollisionException)

Example 4 with User

use of com.firebase.ui.auth.data.model.User in project FirebaseUI-Android by firebase.

the class WelcomeBackPasswordHandlerTest method testSignIn_anonymousUserUpgradeEnabledWithSocialFlow_expectSafeLinksIdpCredentialAndMergeFailure.

@Test
public void testSignIn_anonymousUserUpgradeEnabledWithSocialFlow_expectSafeLinksIdpCredentialAndMergeFailure() {
    setupAnonymousUpgrade();
    mHandler.getOperation().observeForever(mResponseObserver);
    // Fake social response from Facebook
    User user = new User.Builder(FacebookAuthProvider.PROVIDER_ID, TestConstants.EMAIL).build();
    IdpResponse response = new IdpResponse.Builder(user).setToken(TestConstants.TOKEN).setSecret(TestConstants.SECRET).build();
    AuthCredential credential = FacebookAuthProvider.getCredential(TestConstants.TOKEN);
    // 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));
    // Mock linking with Facebook to always work
    when(FakeAuthResult.INSTANCE.getUser().linkWithCredential(credential)).thenReturn(new AutoContinueTask<>(FakeAuthResult.INSTANCE, FakeAuthResult.INSTANCE, true, null));
    // Kick off the sign in flow
    mHandler.startSignIn(TestConstants.EMAIL, TestConstants.PASSWORD, response, credential);
    // 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);
    // Verify that account linking is attempted
    verify(FakeAuthResult.INSTANCE.getUser()).linkWithCredential(credential);
    verifyMergeFailure();
}
Also used : EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) User(com.firebase.ui.auth.data.model.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) IdpResponse(com.firebase.ui.auth.IdpResponse) Test(org.junit.Test)

Example 5 with User

use of com.firebase.ui.auth.data.model.User in project FirebaseUI-Android by firebase.

the class WelcomeBackPasswordHandlerTest method testSignIn_anonymousUserUpgradeEnabledWithEmailFlow_expectValidateCredentialAndMergeFailure.

@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();
}
Also used : EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) User(com.firebase.ui.auth.data.model.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) IdpResponse(com.firebase.ui.auth.IdpResponse) Test(org.junit.Test)

Aggregations

User (com.firebase.ui.auth.data.model.User)14 IdpResponse (com.firebase.ui.auth.IdpResponse)11 AuthCredential (com.google.firebase.auth.AuthCredential)9 FirebaseUiException (com.firebase.ui.auth.FirebaseUiException)8 AuthOperationManager (com.firebase.ui.auth.util.data.AuthOperationManager)8 NonNull (androidx.annotation.NonNull)7 AuthResult (com.google.firebase.auth.AuthResult)7 FirebaseUser (com.google.firebase.auth.FirebaseUser)7 Application (android.app.Application)6 Nullable (androidx.annotation.Nullable)6 Resource (com.firebase.ui.auth.data.model.Resource)6 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)6 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)6 RestrictTo (androidx.annotation.RestrictTo)5 ErrorCodes (com.firebase.ui.auth.ErrorCodes)5 ProfileMerger (com.firebase.ui.auth.data.remote.ProfileMerger)5 ProviderUtils (com.firebase.ui.auth.util.data.ProviderUtils)5 TaskFailureLogger (com.firebase.ui.auth.util.data.TaskFailureLogger)5 SignInViewModelBase (com.firebase.ui.auth.viewmodel.SignInViewModelBase)5 EmailAuthProvider (com.google.firebase.auth.EmailAuthProvider)5