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