Search in sources :

Example 11 with User

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

the class CheckEmailFragment method onActivityCreated.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mHandler = new ViewModelProvider(this).get(CheckEmailHandler.class);
    mHandler.init(getFlowParams());
    FragmentActivity activity = getActivity();
    if (!(activity instanceof CheckEmailListener)) {
        throw new IllegalStateException("Activity must implement CheckEmailListener");
    }
    mListener = (CheckEmailListener) activity;
    mHandler.getOperation().observe(getViewLifecycleOwner(), new ResourceObserver<User>(this, R.string.fui_progress_dialog_checking_accounts) {

        @Override
        protected void onSuccess(@NonNull User user) {
            String email = user.getEmail();
            String provider = user.getProviderId();
            mEmailEditText.setText(email);
            // noinspection ConstantConditions new user
            if (provider == null) {
                mListener.onNewUser(new User.Builder(EmailAuthProvider.PROVIDER_ID, email).setName(user.getName()).setPhotoUri(user.getPhotoUri()).build());
            } else if (provider.equals(EmailAuthProvider.PROVIDER_ID) || provider.equals(EMAIL_LINK_PROVIDER)) {
                mListener.onExistingEmailUser(user);
            } else {
                mListener.onExistingIdpUser(user);
            }
        }

        @Override
        protected void onFailure(@NonNull Exception e) {
            if (e instanceof FirebaseUiException && ((FirebaseUiException) e).getErrorCode() == ErrorCodes.DEVELOPER_ERROR) {
                mListener.onDeveloperFailure(e);
            }
            if (e instanceof FirebaseNetworkException) {
                Snackbar.make(getView(), getString(R.string.fui_no_internet), Snackbar.LENGTH_SHORT).show();
            }
        // Otherwise just let the user enter their data
        }
    });
    if (savedInstanceState != null) {
        return;
    }
    // Check for email
    String email = getArguments().getString(ExtraConstants.EMAIL);
    if (!TextUtils.isEmpty(email)) {
        mEmailEditText.setText(email);
        validateAndProceed();
    } else if (getFlowParams().enableHints) {
        mHandler.fetchCredential();
    }
}
Also used : User(com.firebase.ui.auth.data.model.User) FirebaseNetworkException(com.google.firebase.FirebaseNetworkException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FragmentActivity(androidx.fragment.app.FragmentActivity) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) ViewModelProvider(androidx.lifecycle.ViewModelProvider) FirebaseNetworkException(com.google.firebase.FirebaseNetworkException)

Example 12 with User

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

the class IdpResponse method from.

@NonNull
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public static IdpResponse from(@NonNull Exception e) {
    if (e instanceof FirebaseUiException) {
        return new IdpResponse((FirebaseUiException) e);
    } else if (e instanceof FirebaseAuthAnonymousUpgradeException) {
        return ((FirebaseAuthAnonymousUpgradeException) e).getResponse();
    } else if (e instanceof FirebaseUiUserCollisionException) {
        FirebaseUiUserCollisionException collisionException = (FirebaseUiUserCollisionException) e;
        // Lint complains about providerId not being
        // in the pre-defined set of constants
        @SuppressLint("WrongConstant") User user = new User.Builder(collisionException.getProviderId(), collisionException.getEmail()).build();
        return new IdpResponse(user, /* token= */
        null, /* secret= */
        null, /* isNewUser= */
        false, new FirebaseUiException(collisionException.getErrorCode(), collisionException.getMessage()), collisionException.getCredential());
    } else {
        FirebaseUiException wrapped = new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR, e.getMessage());
        wrapped.setStackTrace(e.getStackTrace());
        return new IdpResponse(wrapped);
    }
}
Also used : User(com.firebase.ui.auth.data.model.User) SuppressLint(android.annotation.SuppressLint) NonNull(androidx.annotation.NonNull) RestrictTo(androidx.annotation.RestrictTo)

Example 13 with User

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

the class WelcomeBackIdpPrompt method onCreate.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fui_welcome_back_idp_prompt_layout);
    mDoneButton = findViewById(R.id.welcome_back_idp_button);
    mProgressBar = findViewById(R.id.top_progress_bar);
    mPromptText = findViewById(R.id.welcome_back_idp_prompt);
    User existingUser = User.getUser(getIntent());
    IdpResponse requestedUserResponse = IdpResponse.fromResultIntent(getIntent());
    ViewModelProvider supplier = new ViewModelProvider(this);
    final LinkingSocialProviderResponseHandler handler = supplier.get(LinkingSocialProviderResponseHandler.class);
    handler.init(getFlowParams());
    if (requestedUserResponse != null) {
        handler.setRequestedSignInCredentialForEmail(ProviderUtils.getAuthCredential(requestedUserResponse), existingUser.getEmail());
    }
    final String providerId = existingUser.getProviderId();
    AuthUI.IdpConfig config = ProviderUtils.getConfigFromIdps(getFlowParams().providers, providerId);
    if (config == null) {
        finish(RESULT_CANCELED, IdpResponse.getErrorIntent(new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, "Firebase login unsuccessful." + " Account linking failed due to provider not enabled by application: " + providerId)));
        return;
    }
    String providerName;
    String genericOAuthProviderId = config.getParams().getString(ExtraConstants.GENERIC_OAUTH_PROVIDER_ID);
    boolean useEmulator = getAuthUI().isUseEmulator();
    switch(providerId) {
        case GoogleAuthProvider.PROVIDER_ID:
            if (useEmulator) {
                mProvider = supplier.get(GenericIdpAnonymousUpgradeLinkingHandler.class).initWith(GenericIdpSignInHandler.getGenericGoogleConfig());
            } else {
                mProvider = supplier.get(GoogleSignInHandler.class).initWith(new GoogleSignInHandler.Params(config, existingUser.getEmail()));
            }
            providerName = getString(R.string.fui_idp_name_google);
            break;
        case FacebookAuthProvider.PROVIDER_ID:
            if (useEmulator) {
                mProvider = supplier.get(GenericIdpAnonymousUpgradeLinkingHandler.class).initWith(GenericIdpSignInHandler.getGenericFacebookConfig());
            } else {
                mProvider = supplier.get(FacebookSignInHandler.class).initWith(config);
            }
            providerName = getString(R.string.fui_idp_name_facebook);
            break;
        default:
            if (TextUtils.equals(providerId, genericOAuthProviderId)) {
                mProvider = supplier.get(GenericIdpAnonymousUpgradeLinkingHandler.class).initWith(config);
                providerName = config.getParams().getString(ExtraConstants.GENERIC_OAUTH_PROVIDER_NAME);
            } else {
                throw new IllegalStateException("Invalid provider id: " + providerId);
            }
    }
    mProvider.getOperation().observe(this, new ResourceObserver<IdpResponse>(this) {

        @Override
        protected void onSuccess(@NonNull IdpResponse response) {
            boolean isGenericIdp = getAuthUI().isUseEmulator() || !AuthUI.SOCIAL_PROVIDERS.contains(response.getProviderType());
            if (isGenericIdp && !response.hasCredentialForLinking() && !handler.hasCredentialForLinking()) {
                // Generic Idp does not return a credential - if this is not a linking flow,
                // the user is already signed in and we are done.
                finish(RESULT_OK, response.toIntent());
                return;
            }
            handler.startSignIn(response);
        }

        @Override
        protected void onFailure(@NonNull Exception e) {
            handler.startSignIn(IdpResponse.from(e));
        }
    });
    mPromptText.setText(getString(R.string.fui_welcome_back_idp_prompt, existingUser.getEmail(), providerName));
    mDoneButton.setOnClickListener(view -> mProvider.startSignIn(getAuth(), WelcomeBackIdpPrompt.this, providerId));
    handler.getOperation().observe(this, new ResourceObserver<IdpResponse>(this) {

        @Override
        protected void onSuccess(@NonNull IdpResponse response) {
            finish(RESULT_OK, response.toIntent());
        }

        @Override
        protected void onFailure(@NonNull Exception e) {
            if (e instanceof FirebaseAuthAnonymousUpgradeException) {
                IdpResponse response = ((FirebaseAuthAnonymousUpgradeException) e).getResponse();
                finish(ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT, response.toIntent());
            } else {
                finish(RESULT_CANCELED, IdpResponse.getErrorIntent(e));
            }
        }
    });
    TextView footerText = findViewById(R.id.email_footer_tos_and_pp_text);
    PrivacyDisclosureUtils.setupTermsOfServiceFooter(this, getFlowParams(), footerText);
}
Also used : User(com.firebase.ui.auth.data.model.User) AuthUI(com.firebase.ui.auth.AuthUI) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) TextView(android.widget.TextView) LinkingSocialProviderResponseHandler(com.firebase.ui.auth.viewmodel.idp.LinkingSocialProviderResponseHandler) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) IdpResponse(com.firebase.ui.auth.IdpResponse) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 14 with User

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

the class WelcomeBackPasswordHandlerTest method testSignIn_linksIdpCredential.

@Test
public void testSignIn_linksIdpCredential() {
    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);
    // Mock sign in to always succeed
    when(mMockAuth.signInWithEmailAndPassword(TestConstants.EMAIL, TestConstants.PASSWORD)).thenReturn(AutoCompleteTask.forSuccess(FakeAuthResult.INSTANCE));
    // Mock linking to always succeed
    when(FakeAuthResult.INSTANCE.getUser().linkWithCredential(credential)).thenReturn(new AutoContinueTask<>(FakeAuthResult.INSTANCE, FakeAuthResult.INSTANCE, true, null));
    // Mock smartlock save to always succeed
    when(mMockCredentials.save(any(Credential.class))).thenReturn(AutoCompleteTask.forSuccess(null));
    // Kick off the sign in flow
    mHandler.startSignIn(TestConstants.EMAIL, TestConstants.PASSWORD, response, credential);
    // Verify that we get a loading event
    verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isLoading()));
    // Verify that sign in is called with the right arguments
    verify(mMockAuth).signInWithEmailAndPassword(TestConstants.EMAIL, TestConstants.PASSWORD);
    // Verify that account linking is attempted
    verify(FakeAuthResult.INSTANCE.getUser()).linkWithCredential(credential);
    // Verify that we get a success event
    verify(mResponseObserver).onChanged(argThat(ResourceMatchers.isSuccess()));
}
Also used : EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) Credential(com.google.android.gms.auth.api.credentials.Credential) User(com.firebase.ui.auth.data.model.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) 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