Search in sources :

Example 11 with FirebaseAuthUserCollisionException

use of com.google.firebase.auth.FirebaseAuthUserCollisionException in project FirebaseUI-Android by firebase.

the class EmailProviderResponseHandler method startSignIn.

public void startSignIn(@NonNull final IdpResponse response, @NonNull final String password) {
    if (!response.isSuccessful()) {
        setResult(Resource.forFailure(response.getError()));
        return;
    }
    if (!response.getProviderType().equals(EmailAuthProvider.PROVIDER_ID)) {
        throw new IllegalStateException("This handler can only be used with the email provider");
    }
    setResult(Resource.forLoading());
    final AuthOperationManager authOperationManager = AuthOperationManager.getInstance();
    final String email = response.getEmail();
    authOperationManager.createOrLinkUserWithEmailAndPassword(getAuth(), getArguments(), email, password).continueWithTask(new ProfileMerger(response)).addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")).addOnSuccessListener(result -> handleSuccess(response, result)).addOnFailureListener(e -> {
        if (e instanceof FirebaseAuthUserCollisionException) {
            if (authOperationManager.canUpgradeAnonymous(getAuth(), getArguments())) {
                AuthCredential credential = EmailAuthProvider.getCredential(email, password);
                handleMergeFailure(credential);
            } else {
                Log.w(TAG, "Got a collision error during a non-upgrade flow", e);
                // Collision with existing user email without anonymous upgrade
                // it should be very hard for the user to even get to this error
                // due to CheckEmailFragment.
                ProviderUtils.fetchTopProvider(getAuth(), getArguments(), email).addOnSuccessListener(new StartWelcomeBackFlow(email)).addOnFailureListener(e1 -> setResult(Resource.forFailure(e1)));
            }
        } else {
            setResult(Resource.forFailure(e));
        }
    });
}
Also used : WelcomeBackIdpPrompt(com.firebase.ui.auth.ui.idp.WelcomeBackIdpPrompt) ProviderUtils(com.firebase.ui.auth.util.data.ProviderUtils) ProfileMerger(com.firebase.ui.auth.data.remote.ProfileMerger) EMAIL_LINK_PROVIDER(com.firebase.ui.auth.AuthUI.EMAIL_LINK_PROVIDER) NonNull(androidx.annotation.NonNull) User(com.firebase.ui.auth.data.model.User) IntentRequiredException(com.firebase.ui.auth.data.model.IntentRequiredException) Resource(com.firebase.ui.auth.data.model.Resource) TaskFailureLogger(com.firebase.ui.auth.util.data.TaskFailureLogger) RestrictTo(androidx.annotation.RestrictTo) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) Log(android.util.Log) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) SignInViewModelBase(com.firebase.ui.auth.viewmodel.SignInViewModelBase) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) AuthCredential(com.google.firebase.auth.AuthCredential) Nullable(androidx.annotation.Nullable) EmailAuthProvider(com.google.firebase.auth.EmailAuthProvider) Application(android.app.Application) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) WelcomeBackEmailLinkPrompt(com.firebase.ui.auth.ui.email.WelcomeBackEmailLinkPrompt) RequestCodes(com.firebase.ui.auth.viewmodel.RequestCodes) AuthResult(com.google.firebase.auth.AuthResult) ErrorCodes(com.firebase.ui.auth.ErrorCodes) IdpResponse(com.firebase.ui.auth.IdpResponse) WelcomeBackPasswordPrompt(com.firebase.ui.auth.ui.email.WelcomeBackPasswordPrompt) AuthCredential(com.google.firebase.auth.AuthCredential) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) TaskFailureLogger(com.firebase.ui.auth.util.data.TaskFailureLogger) ProfileMerger(com.firebase.ui.auth.data.remote.ProfileMerger) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException)

Example 12 with FirebaseAuthUserCollisionException

use of com.google.firebase.auth.FirebaseAuthUserCollisionException in project FirebaseUI-Android by firebase.

the class SocialProviderResponseHandler method startSignIn.

public void startSignIn(@NonNull final IdpResponse response) {
    if (!response.isSuccessful() && !response.isRecoverableErrorResponse()) {
        setResult(Resource.forFailure(response.getError()));
        return;
    }
    if (isEmailOrPhoneProvider(response.getProviderType())) {
        throw new IllegalStateException("This handler cannot be used with email or phone providers");
    }
    setResult(Resource.forLoading());
    // a credential made from the id token/access token cannot be used to sign-in.
    if (response.hasCredentialForLinking()) {
        handleGenericIdpLinkingFlow(response);
        return;
    }
    final AuthCredential credential = ProviderUtils.getAuthCredential(response);
    AuthOperationManager.getInstance().signInAndLinkWithCredential(getAuth(), getArguments(), credential).continueWithTask(new ProfileMerger(response)).addOnSuccessListener(result -> handleSuccess(response, result)).addOnFailureListener(e -> {
        // For some reason disabled users can hit FirebaseAuthUserCollisionException
        // so we have to handle this special case.
        boolean isDisabledUser = (e instanceof FirebaseAuthInvalidUserException);
        if (e instanceof FirebaseAuthException) {
            FirebaseAuthException authEx = (FirebaseAuthException) e;
            FirebaseAuthError fae = FirebaseAuthError.fromException(authEx);
            if (fae == FirebaseAuthError.ERROR_USER_DISABLED) {
                isDisabledUser = true;
            }
        }
        if (isDisabledUser) {
            setResult(Resource.forFailure(new FirebaseUiException(ErrorCodes.ERROR_USER_DISABLED)));
        } else if (e instanceof FirebaseAuthUserCollisionException) {
            final String email = response.getEmail();
            if (email == null) {
                setResult(Resource.forFailure(e));
                return;
            }
            // There can be a collision due to:
            // CASE 1: Anon user signing in with a credential that belongs to an
            // existing user.
            // CASE 2: non - anon user signing in with a credential that does not
            // belong to an existing user, but the email matches an existing user
            // that has another social IDP. We need to link this new IDP to this
            // existing user.
            // CASE 3: CASE 2 with an anonymous user. We link the new IDP to the
            // same account before handling invoking a merge failure.
            ProviderUtils.fetchSortedProviders(getAuth(), getArguments(), email).addOnSuccessListener(providers -> {
                if (providers.contains(response.getProviderType())) {
                    // Case 1
                    handleMergeFailure(credential);
                } else if (providers.isEmpty()) {
                    setResult(Resource.forFailure(new FirebaseUiException(ErrorCodes.DEVELOPER_ERROR, "No supported providers.")));
                } else {
                    // Case 2 & 3 - we need to link
                    startWelcomeBackFlowForLinking(providers.get(0), response);
                }
            }).addOnFailureListener(e1 -> setResult(Resource.forFailure(e1)));
        }
    });
}
Also used : AuthCredential(com.google.firebase.auth.AuthCredential) WelcomeBackIdpPrompt(com.firebase.ui.auth.ui.idp.WelcomeBackIdpPrompt) ProviderUtils(com.firebase.ui.auth.util.data.ProviderUtils) ProfileMerger(com.firebase.ui.auth.data.remote.ProfileMerger) EMAIL_LINK_PROVIDER(com.firebase.ui.auth.AuthUI.EMAIL_LINK_PROVIDER) NonNull(androidx.annotation.NonNull) User(com.firebase.ui.auth.data.model.User) IntentRequiredException(com.firebase.ui.auth.data.model.IntentRequiredException) Intent(android.content.Intent) Resource(com.firebase.ui.auth.data.model.Resource) PhoneAuthProvider(com.google.firebase.auth.PhoneAuthProvider) RestrictTo(androidx.annotation.RestrictTo) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseAuthInvalidUserException(com.google.firebase.auth.FirebaseAuthInvalidUserException) SignInViewModelBase(com.firebase.ui.auth.viewmodel.SignInViewModelBase) TextUtils(android.text.TextUtils) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) FirebaseAuthError(com.firebase.ui.auth.util.FirebaseAuthError) AuthCredential(com.google.firebase.auth.AuthCredential) List(java.util.List) Nullable(androidx.annotation.Nullable) EmailAuthProvider(com.google.firebase.auth.EmailAuthProvider) Application(android.app.Application) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) WelcomeBackEmailLinkPrompt(com.firebase.ui.auth.ui.email.WelcomeBackEmailLinkPrompt) FirebaseAuthException(com.google.firebase.auth.FirebaseAuthException) RequestCodes(com.firebase.ui.auth.viewmodel.RequestCodes) AuthResult(com.google.firebase.auth.AuthResult) ErrorCodes(com.firebase.ui.auth.ErrorCodes) Activity(android.app.Activity) IdpResponse(com.firebase.ui.auth.IdpResponse) WelcomeBackPasswordPrompt(com.firebase.ui.auth.ui.email.WelcomeBackPasswordPrompt) FirebaseAuthInvalidUserException(com.google.firebase.auth.FirebaseAuthInvalidUserException) FirebaseAuthError(com.firebase.ui.auth.util.FirebaseAuthError) ProfileMerger(com.firebase.ui.auth.data.remote.ProfileMerger) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) FirebaseAuthException(com.google.firebase.auth.FirebaseAuthException)

Example 13 with FirebaseAuthUserCollisionException

use of com.google.firebase.auth.FirebaseAuthUserCollisionException in project FirebaseUI-Android by firebase.

the class RegisterEmailFragment method registerUser.

private void registerUser(final String email, final String name, final String password) {
    mHelper.getFirebaseAuth().createUserWithEmailAndPassword(email, password).addOnFailureListener(new TaskFailureLogger(TAG, "Error creating user")).addOnSuccessListener(new OnSuccessListener<AuthResult>() {

        @Override
        public void onSuccess(AuthResult authResult) {
            // Set display name
            UserProfileChangeRequest changeNameRequest = new UserProfileChangeRequest.Builder().setDisplayName(name).setPhotoUri(mUser.getPhotoUri()).build();
            final FirebaseUser user = authResult.getUser();
            user.updateProfile(changeNameRequest).addOnFailureListener(new TaskFailureLogger(TAG, "Error setting display name")).addOnCompleteListener(new OnCompleteListener<Void>() {

                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // This executes even if the name change fails, since
                    // the account creation succeeded and we want to save
                    // the credential to SmartLock (if enabled).
                    mHelper.saveCredentialsOrFinish(mSaveSmartLock, getActivity(), user, password, new IdpResponse(EmailAuthProvider.PROVIDER_ID, email));
                }
            });
        }
    }).addOnFailureListener(getActivity(), new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
            mHelper.dismissDialog();
            if (e instanceof FirebaseAuthWeakPasswordException) {
                // Password too weak
                mPasswordInput.setError(getResources().getQuantityString(R.plurals.error_weak_password, R.integer.min_password_length));
            } else if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Email address is malformed
                mEmailInput.setError(getString(R.string.invalid_email_address));
            } else if (e instanceof FirebaseAuthUserCollisionException) {
                // Collision with existing user email, it should be very hard for
                // the user to even get to this error due to CheckEmailFragment.
                mEmailInput.setError(getString(R.string.error_user_collision));
            } else {
                // General error message, this branch should not be invoked but
                // covers future API changes
                mEmailInput.setError(getString(R.string.email_account_creation_error));
            }
        }
    });
}
Also used : TaskFailureLogger(com.firebase.ui.auth.ui.TaskFailureLogger) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) UserProfileChangeRequest(com.google.firebase.auth.UserProfileChangeRequest) AuthResult(com.google.firebase.auth.AuthResult) FirebaseUser(com.google.firebase.auth.FirebaseUser) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 14 with FirebaseAuthUserCollisionException

use of com.google.firebase.auth.FirebaseAuthUserCollisionException in project FirebaseUI-Android by firebase.

the class CredentialSignInHandlerTest method testSignInFailed_withPasswordAccountAlreadyLinked.

@Test
public void testSignInFailed_withPasswordAccountAlreadyLinked() {
    AppCompatBase mockActivity = mock(AppCompatBase.class);
    ActivityHelper mockActivityHelper = mock(ActivityHelper.class);
    FirebaseAuth mockFirebaseAuth = mock(FirebaseAuth.class);
    IdpResponse idpResponse = new IdpResponse(GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL);
    CredentialSignInHandler credentialSignInHandler = new CredentialSignInHandler(mockActivity, mockActivityHelper, null, RC_ACCOUNT_LINK, idpResponse);
    Task mockTask = mock(Task.class);
    FlowParameters mockFlowParams = mock(FlowParameters.class);
    // pretend there was already an account with this email
    when(mockTask.getException()).thenReturn(new FirebaseAuthUserCollisionException(LINKING_ERROR, LINKING_EXPLANATION));
    when(mockActivityHelper.getFirebaseAuth()).thenReturn(mockFirebaseAuth);
    when(mockActivityHelper.getFlowParams()).thenReturn(mockFlowParams);
    // pretend the account has a Password account linked already
    when(mockFirebaseAuth.fetchProvidersForEmail(TestConstants.EMAIL)).thenReturn(new AutoCompleteTask<ProviderQueryResult>(new FakeProviderQueryResult(Arrays.asList(EmailAuthProvider.PROVIDER_ID)), true, null));
    credentialSignInHandler.onComplete(mockTask);
    ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
    ArgumentCaptor<Integer> intCaptor = ArgumentCaptor.forClass(Integer.class);
    verify(mockActivity).startActivityForResult(intentCaptor.capture(), intCaptor.capture());
    Intent capturedIntent = intentCaptor.getValue();
    assertEquals(RC_ACCOUNT_LINK, (int) intCaptor.getValue());
    assertEquals(WelcomeBackPasswordPrompt.class.getName(), capturedIntent.getComponent().getClassName());
    assertEquals(TestConstants.EMAIL, IdpResponse.fromResultIntent(capturedIntent).getEmail());
}
Also used : Task(com.google.android.gms.tasks.Task) AutoCompleteTask(com.firebase.ui.auth.testhelpers.AutoCompleteTask) AppCompatBase(com.firebase.ui.auth.ui.AppCompatBase) Intent(android.content.Intent) FakeProviderQueryResult(com.firebase.ui.auth.testhelpers.FakeProviderQueryResult) ProviderQueryResult(com.google.firebase.auth.ProviderQueryResult) ActivityHelper(com.firebase.ui.auth.ui.ActivityHelper) FlowParameters(com.firebase.ui.auth.ui.FlowParameters) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FakeProviderQueryResult(com.firebase.ui.auth.testhelpers.FakeProviderQueryResult) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) IdpResponse(com.firebase.ui.auth.IdpResponse) WelcomeBackPasswordPrompt(com.firebase.ui.auth.ui.accountlink.WelcomeBackPasswordPrompt) Test(org.junit.Test)

Example 15 with FirebaseAuthUserCollisionException

use of com.google.firebase.auth.FirebaseAuthUserCollisionException in project BloodHub by kazijehangir.

the class IndividualRegistrationActivity method registerNewUser.

private void registerNewUser() {
    email = mEmailView.getText().toString().trim();
    password = mPasswordView.getText().toString().trim();
    uname = username.getText().toString();
    bgroup = bloodGroup.getSelectedItem().toString();
    if (uname.isEmpty()) {
        Toast.makeText(this, "You forgot to enter your name.", Toast.LENGTH_SHORT).show();
    } else {
        if (!isEmailValid(email)) {
            Toast.makeText(this, "Not a valid email address", Toast.LENGTH_SHORT).show();
        } else {
            if (!isPasswordValid(password)) {
                Toast.makeText(this, "Password is too short, minimum length is 6.", Toast.LENGTH_SHORT).show();
            } else {
                if (bgroup.contentEquals("Blood Group")) {
                    Toast.makeText(this, "You forgot to choose your blood group.", Toast.LENGTH_SHORT).show();
                } else {
                    // register user with firebase
                    // progressBar.setVisibility(View.VISIBLE);
                    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {

                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Context context = getApplicationContext();
                            // progressBar.setVisibility(View.GONE);
                            if (task.isSuccessful()) {
                                FirebaseUser user = mAuth.getCurrentUser();
                                Toast.makeText(context, "Registration Successful!", Toast.LENGTH_SHORT).show();
                                // set default subscriptions
                                int id = Arrays.asList(getResources().getStringArray(R.array.blood_groups)).indexOf(bgroup);
                                FirebaseMessaging.getInstance().subscribeToTopic("Request_" + id);
                                FirebaseMessaging.getInstance().subscribeToTopic("URGENT");
                                // take user to main screen
                                sendVerificationEmail();
                                writeNewUser(user.getUid(), user.getEmail());
                                Intent intent = new Intent(context, LoginActivity.class);
                                startActivity(intent);
                            } else {
                                if (task.getException() instanceof FirebaseAuthUserCollisionException) {
                                    Toast.makeText(context, "User with this email already exists.", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(context, "Error creating user", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });
                }
            }
        }
    }
}
Also used : Context(android.content.Context) AuthResult(com.google.firebase.auth.AuthResult) Intent(android.content.Intent) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseUser(com.google.firebase.auth.FirebaseUser)

Aggregations

FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)22 IdpResponse (com.firebase.ui.auth.IdpResponse)15 Resource (com.firebase.ui.auth.data.model.Resource)15 AuthCredential (com.google.firebase.auth.AuthCredential)14 Test (org.junit.Test)12 FirebaseUser (com.google.firebase.auth.FirebaseUser)10 InOrder (org.mockito.InOrder)10 AuthResult (com.google.firebase.auth.AuthResult)9 Intent (android.content.Intent)7 User (com.firebase.ui.auth.data.model.User)7 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)7 FirebaseAuthAnonymousUpgradeException (com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException)6 FakeSignInMethodQueryResult (com.firebase.ui.auth.testhelpers.FakeSignInMethodQueryResult)6 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)6 Application (android.app.Application)5 NonNull (androidx.annotation.NonNull)5 Nullable (androidx.annotation.Nullable)5 ErrorCodes (com.firebase.ui.auth.ErrorCodes)5 FirebaseUiException (com.firebase.ui.auth.FirebaseUiException)5 IntentRequiredException (com.firebase.ui.auth.data.model.IntentRequiredException)5