Search in sources :

Example 56 with IdpResponse

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

the class WelcomeBackPasswordHandler method startSignIn.

/**
 * Kick off the sign-in process.
 */
public void startSignIn(@NonNull final String email, @NonNull final String password, @NonNull final IdpResponse inputResponse, @Nullable final AuthCredential credential) {
    setResult(Resource.forLoading());
    // Store the password before signing in so it can be used for later credential building
    mPendingPassword = password;
    // Build appropriate IDP response based on inputs
    final IdpResponse outputResponse;
    if (credential == null) {
        // New credential for the email provider
        outputResponse = new IdpResponse.Builder(new User.Builder(EmailAuthProvider.PROVIDER_ID, email).build()).build();
    } else {
        // New credential for an IDP (Phone or Social)
        outputResponse = new IdpResponse.Builder(inputResponse.getUser()).setPendingCredential(inputResponse.getCredentialForLinking()).setToken(inputResponse.getIdpToken()).setSecret(inputResponse.getIdpSecret()).build();
    }
    final AuthOperationManager authOperationManager = AuthOperationManager.getInstance();
    if (authOperationManager.canUpgradeAnonymous(getAuth(), getArguments())) {
        final AuthCredential credToValidate = EmailAuthProvider.getCredential(email, password);
        // Check to see if we need to link (for social providers with the same email)
        if (AuthUI.SOCIAL_PROVIDERS.contains(inputResponse.getProviderType())) {
            // Add the provider to the same account before triggering a merge failure.
            authOperationManager.safeLink(credToValidate, credential, getArguments()).addOnSuccessListener(result -> handleMergeFailure(credToValidate)).addOnFailureListener(e -> setResult(Resource.forFailure(e)));
        } else {
            // The user has not tried to log in with a federated IDP containing the same email.
            // In this case, we just need to verify that the credential they provided is valid.
            // No linking is done for non-federated IDPs.
            // A merge failure occurs because the account exists and the user is anonymous.
            authOperationManager.validateCredential(credToValidate, getArguments()).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    handleMergeFailure(credToValidate);
                } else {
                    setResult(Resource.forFailure(task.getException()));
                }
            });
        }
    } else {
        // Kick off the flow including signing in, linking accounts, and saving with SmartLock
        getAuth().signInWithEmailAndPassword(email, password).continueWithTask(task -> {
            // Forward task failure by asking for result
            AuthResult result = task.getResult(Exception.class);
            // Task succeeded, link user if necessary
            if (credential == null) {
                return Tasks.forResult(result);
            } else {
                return result.getUser().linkWithCredential(credential).continueWithTask(new ProfileMerger(outputResponse)).addOnFailureListener(new TaskFailureLogger(TAG, "linkWithCredential+merge failed."));
            }
        }).addOnSuccessListener(result -> handleSuccess(outputResponse, result)).addOnFailureListener(e -> setResult(Resource.forFailure(e))).addOnFailureListener(new TaskFailureLogger(TAG, "signInWithEmailAndPassword failed."));
    }
}
Also used : AuthCredential(com.google.firebase.auth.AuthCredential) ProfileMerger(com.firebase.ui.auth.data.remote.ProfileMerger) NonNull(androidx.annotation.NonNull) User(com.firebase.ui.auth.data.model.User) SignInViewModelBase(com.firebase.ui.auth.viewmodel.SignInViewModelBase) Resource(com.firebase.ui.auth.data.model.Resource) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) TaskFailureLogger(com.firebase.ui.auth.util.data.TaskFailureLogger) Task(com.google.android.gms.tasks.Task) AuthCredential(com.google.firebase.auth.AuthCredential) Tasks(com.google.android.gms.tasks.Tasks) Nullable(androidx.annotation.Nullable) RestrictTo(androidx.annotation.RestrictTo) EmailAuthProvider(com.google.firebase.auth.EmailAuthProvider) Application(android.app.Application) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) AuthUI(com.firebase.ui.auth.AuthUI) Continuation(com.google.android.gms.tasks.Continuation) AuthResult(com.google.firebase.auth.AuthResult) IdpResponse(com.firebase.ui.auth.IdpResponse) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) TaskFailureLogger(com.firebase.ui.auth.util.data.TaskFailureLogger) AuthResult(com.google.firebase.auth.AuthResult) ProfileMerger(com.firebase.ui.auth.data.remote.ProfileMerger) IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 57 with IdpResponse

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

the class EmailLinkPersistanceManagerTest method testSaveAndRetrieveIdpResonseForLinking_saveEmailFirst.

@Test
public void testSaveAndRetrieveIdpResonseForLinking_saveEmailFirst() {
    IdpResponse response = buildIdpResponse();
    mPersistenceManager.saveEmail(ApplicationProvider.getApplicationContext(), TestConstants.EMAIL, TestConstants.SESSION_ID, TestConstants.UID);
    mPersistenceManager.saveIdpResponseForLinking(ApplicationProvider.getApplicationContext(), response);
    SessionRecord sessionRecord = mPersistenceManager.retrieveSessionRecord(ApplicationProvider.getApplicationContext());
    assertThat(sessionRecord.getEmail()).isEqualTo(TestConstants.EMAIL);
    assertThat(sessionRecord.getSessionId()).isEqualTo(TestConstants.SESSION_ID);
    assertThat(sessionRecord.getAnonymousUserId()).isEqualTo(TestConstants.UID);
    assertThat(sessionRecord.getIdpResponseForLinking()).isEqualTo(response);
}
Also used : IdpResponse(com.firebase.ui.auth.IdpResponse) SessionRecord(com.firebase.ui.auth.util.data.EmailLinkPersistenceManager.SessionRecord) Test(org.junit.Test)

Example 58 with IdpResponse

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

the class SignInViewModelBase method handleMergeFailure.

protected void handleMergeFailure(@NonNull AuthCredential credential) {
    IdpResponse failureResponse = new IdpResponse.Builder().setPendingCredential(credential).build();
    handleMergeFailure(failureResponse);
}
Also used : IdpResponse(com.firebase.ui.auth.IdpResponse)

Example 59 with IdpResponse

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

the class EmailLinkSignInHandlerTest method testStartSignIn_linkingFlowWithAnonymousUpgradeEnabled_failedLinkPropagated.

@Test
@SuppressWarnings("all")
public void testStartSignIn_linkingFlowWithAnonymousUpgradeEnabled_failedLinkPropagated() {
    mHandler.getOperation().observeForever(mResponseObserver);
    setupAnonymousUpgrade();
    when(mMockAuth.isSignInWithEmailLink(any(String.class))).thenReturn(true);
    mPersistenceManager.saveEmail(ApplicationProvider.getApplicationContext(), TestConstants.EMAIL, TestConstants.SESSION_ID, TestConstants.UID);
    mPersistenceManager.saveIdpResponseForLinking(ApplicationProvider.getApplicationContext(), buildFacebookIdpResponse());
    // Need to control FirebaseAuth's return values
    AuthOperationManager authOperationManager = AuthOperationManager.getInstance();
    authOperationManager.mScratchAuth = mScratchMockAuth;
    when(mScratchMockAuth.signInWithCredential(any(AuthCredential.class))).thenReturn(AutoCompleteTask.forSuccess(mMockAuthResult));
    // Mock linking with Facebook to always work
    when(mMockAuthResult.getUser().linkWithCredential(any(AuthCredential.class))).thenReturn(AutoContinueTask.<AuthResult>forFailure(new Exception("FAILED")));
    mHandler.startSignIn();
    // Verify sign in was called
    verify(mScratchMockAuth).signInWithCredential(any(AuthCredential.class));
    // Validate linking was called
    verify(mMockAuthResult.getUser()).linkWithCredential(any(FacebookAuthCredential.class));
    // Validate that the data was cleared
    assertThat(mPersistenceManager.retrieveSessionRecord(ApplicationProvider.getApplicationContext())).isNull();
    // Validate failure
    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();
}
Also used : FacebookAuthCredential(com.google.firebase.auth.FacebookAuthCredential) EmailAuthCredential(com.google.firebase.auth.EmailAuthCredential) AuthCredential(com.google.firebase.auth.AuthCredential) AuthOperationManager(com.firebase.ui.auth.util.data.AuthOperationManager) InOrder(org.mockito.InOrder) Resource(com.firebase.ui.auth.data.model.Resource) FacebookAuthCredential(com.google.firebase.auth.FacebookAuthCredential) FirebaseAuthAnonymousUpgradeException(com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) FirebaseUiException(com.firebase.ui.auth.FirebaseUiException) IdpResponse(com.firebase.ui.auth.IdpResponse) Test(org.junit.Test)

Example 60 with IdpResponse

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

the class EmailLinkPersistenceManager method retrieveSessionRecord.

@Nullable
public SessionRecord retrieveSessionRecord(@NonNull Context context) {
    Preconditions.checkNotNull(context);
    SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
    String email = sharedPreferences.getString(KEY_EMAIL, null);
    String sessionId = sharedPreferences.getString(KEY_SESSION_ID, null);
    if (email == null || sessionId == null) {
        return null;
    }
    String anonymousUserId = sharedPreferences.getString(KEY_ANONYMOUS_USER_ID, null);
    String provider = sharedPreferences.getString(KEY_PROVIDER, null);
    String idpToken = sharedPreferences.getString(KEY_IDP_TOKEN, null);
    String idpSecret = sharedPreferences.getString(KEY_IDP_SECRET, null);
    SessionRecord sessionRecord = new SessionRecord(sessionId, anonymousUserId).setEmail(email);
    if (provider != null && (idpToken != null || mCredentialForLinking != null)) {
        IdpResponse response = new IdpResponse.Builder(new User.Builder(provider, email).build()).setPendingCredential(mCredentialForLinking).setToken(idpToken).setSecret(idpSecret).setNewUser(false).build();
        sessionRecord.setIdpResponseForLinking(response);
    }
    mCredentialForLinking = null;
    return sessionRecord;
}
Also used : User(com.firebase.ui.auth.data.model.User) SharedPreferences(android.content.SharedPreferences) IdpResponse(com.firebase.ui.auth.IdpResponse) Nullable(androidx.annotation.Nullable)

Aggregations

IdpResponse (com.firebase.ui.auth.IdpResponse)81 Test (org.junit.Test)45 Resource (com.firebase.ui.auth.data.model.Resource)35 AuthCredential (com.google.firebase.auth.AuthCredential)31 InOrder (org.mockito.InOrder)31 FirebaseUiException (com.firebase.ui.auth.FirebaseUiException)22 FirebaseAuthAnonymousUpgradeException (com.firebase.ui.auth.FirebaseAuthAnonymousUpgradeException)19 FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)19 User (com.firebase.ui.auth.data.model.User)18 FirebaseUser (com.google.firebase.auth.FirebaseUser)15 AuthOperationManager (com.firebase.ui.auth.util.data.AuthOperationManager)12 EmailAuthCredential (com.google.firebase.auth.EmailAuthCredential)11 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)10 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)10 AuthResult (com.google.firebase.auth.AuthResult)10 Intent (android.content.Intent)9 Nullable (androidx.annotation.Nullable)9 IntentRequiredException (com.firebase.ui.auth.data.model.IntentRequiredException)9 Task (com.google.android.gms.tasks.Task)9 Application (android.app.Application)8