com.google.android.gms.auth.api.credentials.Credential Java Examples

The following examples show how to use com.google.android.gms.auth.api.credentials.Credential. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivity.java    From android-credentials with Apache License 2.0 8 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);

    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleGoogleSignIn(task);
    } else if (requestCode == RC_CREDENTIALS_READ) {
        mIsResolving = false;
        if (resultCode == RESULT_OK) {
            Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            handleCredential(credential);
        }
    } else if (requestCode == RC_CREDENTIALS_SAVE) {
        mIsResolving = false;
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
        } else {
            Log.w(TAG, "Credential save failed.");
        }
    }
}
 
Example #2
Source File: SmartLock.java    From easygoogle with Apache License 2.0 6 votes vote down vote up
/**
 * Begin the process of retrieving a {@link Credential} for the device user. This can have
 * a few different results:
 *   1) If the user has auto sign-in enabled and exactly one previously saved credential,
 *      {@link SmartLockListener#onCredentialRetrieved(Credential)} will be called and
 *      you can sign the user in immediately.
 *   2) If the user has multiple saved credentials or one saved credential and has disabled
 *      auto sign-in, you will get the callback {@link SmartLockListener#onShouldShowCredentialPicker()}
 *      at which point you can choose to show the picker dialog to continue.
 *   3) If the user has no saved credentials or cancels the operation, you will receive the
 *      {@link SmartLockListener#onCredentialRetrievalFailed()} callback.
 */
public void getCredentials() {
    CredentialRequest request = buildCredentialRequest();

    Auth.CredentialsApi.request(getFragment().getGoogleApiClient(), request)
            .setResultCallback(new ResultCallback<CredentialRequestResult>() {
                @Override
                public void onResult(CredentialRequestResult result) {
                    if (result.getStatus().isSuccess()) {
                        // Single credential, auto sign-in
                        Credential credential = result.getCredential();
                        getListener().onCredentialRetrieved(credential);
                    } else if (result.getStatus().hasResolution() &&
                            result.getStatus().getStatusCode() != CommonStatusCodes.SIGN_IN_REQUIRED) {
                        // Multiple credentials or auto-sign in disabled.  If the status
                        // code is SIGN_IN_REQUIRED then it is a hint credential, which we
                        // do not want at this point.
                        getListener().onShouldShowCredentialPicker();
                    } else {
                        // Could not retrieve credentials
                        getListener().onCredentialRetrievalFailed();
                    }
                }
            });
}
 
Example #3
Source File: SmartLock.java    From easygoogle with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RC_READ) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            getListener().onCredentialRetrieved(credential);
        } else {
            getListener().onCredentialRetrievalFailed();
        }

        return true;
    }

    if (requestCode == RC_SAVE) {
        if (resultCode == Activity.RESULT_OK) {
            Log.d(TAG, "RC_SAVE: Ok");
        } else {
            Log.d(TAG, "RC_SAVE: Failure");
        }

        return true;
    }

    return false;
}
 
Example #4
Source File: MainActivity.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);

    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleGoogleSignIn(task);
    } else if (requestCode == RC_CREDENTIALS_READ) {
        mIsResolving = false;
        if (resultCode == RESULT_OK) {
            Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            handleCredential(credential);
        }
    } else if (requestCode == RC_CREDENTIALS_SAVE) {
        mIsResolving = false;
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
        } else {
            Log.w(TAG, "Credential save failed.");
        }
    }
}
 
Example #5
Source File: MainActivity.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
private void saveCredential(Credential credential) {
    if (credential == null) {
        Log.w(TAG, "Ignoring null credential.");
        return;
    }

    mCredentialsClient.save(mCredential).addOnCompleteListener(
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "save:SUCCESS");
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // Saving the credential can sometimes require showing some UI
                        // to the user, which means we need to fire this resolution.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_CREDENTIALS_SAVE);
                    } else {
                        Log.w(TAG, "save:FAILURE", e);
                        Toast.makeText(MainActivity.this,
                                "Unexpected error, see logs for detals",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
 
Example #6
Source File: MainActivity.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
private void onEmailSaveClicked() {
    String email = ((EditText) findViewById(R.id.edit_text_email)).getText().toString();
    String password = ((EditText) findViewById(R.id.edit_text_password)).getText().toString();

    if (email.length() == 0|| password.length() == 0) {
        Log.w(TAG, "Blank email or password, can't save Credential.");
        Toast.makeText(this, "Email/Password must not be blank.", Toast.LENGTH_SHORT).show();
        return;
    }

    Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .build();

    saveCredential(credential);
}
 
Example #7
Source File: CredentialUtils.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Build a credential for the specified {@link FirebaseUser} with optional password and {@link
 * IdpResponse}.
 * <p>
 * If the credential cannot be built (for example, empty email) then will return {@code null}.
 */
@Nullable
public static Credential buildCredential(@NonNull FirebaseUser user,
                                         @Nullable String password,
                                         @Nullable String accountType) {
    String email = user.getEmail();
    String phone = user.getPhoneNumber();
    Uri profilePictureUri =
            user.getPhotoUrl() == null ? null : Uri.parse(user.getPhotoUrl().toString());

    if (TextUtils.isEmpty(email) && TextUtils.isEmpty(phone)) {
        Log.w(TAG, "User (accountType=" + accountType + ") has no email or phone number, cannot build credential.");
        return null;
    }
    if (password == null && accountType == null) {
        Log.w(TAG, "User has no accountType or password, cannot build credential.");
        return null;
    }

    Credential.Builder builder =
            new Credential.Builder(TextUtils.isEmpty(email) ? phone : email)
                    .setName(user.getDisplayName())
                    .setProfilePictureUri(profilePictureUri);

    if (TextUtils.isEmpty(password)) {
        builder.setAccountType(accountType);
    } else {
        builder.setPassword(password);
    }

    return builder.build();
}
 
Example #8
Source File: MainActivity.java    From android-credentials with Apache License 2.0 6 votes vote down vote up
private void onEmailSaveClicked() {
    String email = ((EditText) findViewById(R.id.edit_text_email)).getText().toString();
    String password = ((EditText) findViewById(R.id.edit_text_password)).getText().toString();

    if (email.length() == 0|| password.length() == 0) {
        Log.w(TAG, "Blank email or password, can't save Credential.");
        Toast.makeText(this, "Email/Password must not be blank.", Toast.LENGTH_SHORT).show();
        return;
    }

    Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .build();

    saveCredential(credential);
}
 
Example #9
Source File: AuthUI.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Make a list of {@link Credential} from a FirebaseUser. Useful for deleting Credentials, not
 * for saving since we don't have access to the password.
 */
private static List<Credential> getCredentialsFromFirebaseUser(@NonNull FirebaseUser user) {
    if (TextUtils.isEmpty(user.getEmail()) && TextUtils.isEmpty(user.getPhoneNumber())) {
        return Collections.emptyList();
    }

    List<Credential> credentials = new ArrayList<>();
    for (UserInfo userInfo : user.getProviderData()) {
        if (FirebaseAuthProvider.PROVIDER_ID.equals(userInfo.getProviderId())) {
            continue;
        }

        String type = ProviderUtils.providerIdToAccountType(userInfo.getProviderId());
        if (type == null) {
            // Since the account type is null, we've got an email credential. Adding a fake
            // password is the only way to tell Smart Lock that this is an email credential.
            credentials.add(CredentialUtils.buildCredentialOrThrow(user, "pass", null));
        } else {
            credentials.add(CredentialUtils.buildCredentialOrThrow(user, null, type));
        }
    }

    return credentials;
}
 
Example #10
Source File: CheckEmailHandler.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode != RequestCodes.CRED_HINT || resultCode != Activity.RESULT_OK) { return; }

    setResult(Resource.<User>forLoading());
    final Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
    final String email = credential.getId();
    ProviderUtils.fetchTopProvider(getAuth(), getArguments(), email)
            .addOnCompleteListener(new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    if (task.isSuccessful()) {
                        setResult(Resource.forSuccess(new User.Builder(task.getResult(), email)
                                .setName(credential.getName())
                                .setPhotoUri(credential.getProfilePictureUri())
                                .build()));
                    } else {
                        setResult(Resource.<User>forFailure(task.getException()));
                    }
                }
            });
}
 
Example #11
Source File: PhoneNumberHelper.java    From react-native-sms-retriever with MIT License 6 votes vote down vote up
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    super.onActivityResult(activity, requestCode, resultCode, data);

    if (requestCode == REQUEST_PHONE_NUMBER_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            final Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            final String phoneNumber = credential.getId();
            promiseResolve(phoneNumber);
            callAndResetListener();
            return;
        }
    }

    promiseReject(ACTIVITY_RESULT_NOOK_ERROR_TYPE, ACTIVITY_RESULT_NOOK_ERROR_MESSAGE);
    callAndResetListener();
}
 
Example #12
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
private void handleCredential(Credential credential) {
    mCredential = credential;

    Log.d(TAG, "handleCredential:" + credential.getAccountType() + ":" + credential.getId());
    if (IdentityProviders.GOOGLE.equals(credential.getAccountType())) {
        // Google account, rebuild GoogleApiClient to set account name and then try
        buildClients(credential.getId());
        googleSilentSignIn();
    } else {
        // Email/password account
        String status = String.format("Signed in as %s", credential.getId());
        ((TextView) findViewById(R.id.text_email_status)).setText(status);
    }
}
 
Example #13
Source File: MainActivity.java    From easygoogle with Apache License 2.0 5 votes vote down vote up
@Override
public void onCredentialRetrieved(Credential credential) {
    ((TextView) findViewById(R.id.smartlock_status)).setText(R.string.status_credential_retrieved);
    mCredential = credential;
    mUsernameField.setText(credential.getId());
    mPasswordField.setText(credential.getPassword());
}
 
Example #14
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
private void saveCredential(Credential credential) {
    if (credential == null) {
        Log.w(TAG, "Ignoring null credential.");
        return;
    }

    mCredentialsClient.save(mCredential).addOnCompleteListener(
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "save:SUCCESS");
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // Saving the credential can sometimes require showing some UI
                        // to the user, which means we need to fire this resolution.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_CREDENTIALS_SAVE);
                    } else {
                        Log.w(TAG, "save:FAILURE", e);
                        Toast.makeText(MainActivity.this,
                                "Unexpected error, see logs for detals",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
 
Example #15
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
private void handleGoogleSignIn(Task<GoogleSignInAccount> completedTask) {
    Log.d(TAG, "handleGoogleSignIn:" + completedTask);

    boolean isSignedIn = (completedTask != null) && completedTask.isSuccessful();
    if (isSignedIn) {
        // Display signed-in UI
        GoogleSignInAccount gsa = completedTask.getResult();
        String status = String.format("Signed in as %s (%s)", gsa.getDisplayName(),
                gsa.getEmail());
        ((TextView) findViewById(R.id.text_google_status)).setText(status);

        // Save Google Sign In to SmartLock
        Credential credential = new Credential.Builder(gsa.getEmail())
                .setAccountType(IdentityProviders.GOOGLE)
                .setName(gsa.getDisplayName())
                .setProfilePictureUri(gsa.getPhotoUrl())
                .build();

        saveCredential(credential);
    } else {
        // Display signed-out UI
        ((TextView) findViewById(R.id.text_google_status)).setText(R.string.signed_out);
    }

    findViewById(R.id.button_google_sign_in).setEnabled(!isSignedIn);
    findViewById(R.id.button_google_sign_out).setEnabled(isSignedIn);
    findViewById(R.id.button_google_revoke).setEnabled(isSignedIn);
}
 
Example #16
Source File: SignInKickstarter.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
private void handleCredential(final Credential credential) {
    String id = credential.getId();
    String password = credential.getPassword();
    if (TextUtils.isEmpty(password)) {
        String identity = credential.getAccountType();
        if (identity == null) {
            startAuthMethodChoice();
        } else {
            redirectSignIn(
                    ProviderUtils.accountTypeToProviderId(credential.getAccountType()), id);
        }
    } else {
        final IdpResponse response = new IdpResponse.Builder(
                new User.Builder(EmailAuthProvider.PROVIDER_ID, id).build()).build();

        setResult(Resource.<IdpResponse>forLoading());
        getAuth().signInWithEmailAndPassword(id, password)
                .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult result) {
                        handleSuccess(response, result);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        if (e instanceof FirebaseAuthInvalidUserException
                                || e instanceof FirebaseAuthInvalidCredentialsException) {
                            // In this case the credential saved in SmartLock was not
                            // a valid credential, we should delete it from SmartLock
                            // before continuing.
                            GoogleApiUtils.getCredentialsClient(getApplication())
                                    .delete(credential);
                        }
                        startAuthMethodChoice();
                    }
                });
    }
}
 
Example #17
Source File: PhoneNumberActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_HINT) {
        if (resultCode == RESULT_OK) {
            Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
            ui.setPhoneNumber(cred.getId());
        } else {
            ui.focusPhoneNumber();
        }
    }
}
 
Example #18
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
/**
 * Process a Credential object retrieved from a successful request.
 * @param credential the Credential to process.
 * @param isHint true if the Credential is hint-only, false otherwise.
 */
private void processRetrievedCredential(Credential credential, boolean isHint) {
    Log.d(TAG, "Credential Retrieved: " + credential.getId() + ":" +
            anonymizePassword(credential.getPassword()));

    // If the Credential is not a hint, we should store it an enable the delete button.
    // If it is a hint, skip this because a hint cannot be deleted.
    if (!isHint) {
        showToast("Credential Retrieved");
        mCurrentCredential = credential;
        findViewById(R.id.button_delete_loaded_credential).setEnabled(true);
    } else {
        showToast("Credential Hint Retrieved");
    }

    mEmailField.setText(credential.getId());
    mPasswordField.setText(credential.getPassword());

    if (!credential.getIdTokens().isEmpty()) {
        IdToken idToken = credential.getIdTokens().get(0);

        // For the purposes of this sample we are using a background service in place of a real
        // web server. The client sends the Id Token to the server which uses the Google
        // APIs Client Library for Java to verify the token and gain a signed assertion
        // of the user's email address. This can be used to confirm the user's identity
        // and sign the user in even without providing a password.
        Intent intent = new Intent(this, MockServer.class)
                .putExtra(MockServer.EXTRA_IDTOKEN, idToken.getIdToken());
        startService(intent);
    } else {
        // This state is reached if non-Google accounts are added to Gmail:
        // https://support.google.com/mail/answer/6078445
        Log.d(TAG, "Credential does not contain ID Tokens.");
    }
}
 
Example #19
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
    hideProgress();

    switch (requestCode) {
        case RC_HINT:
            // Drop into handling for RC_READ
        case RC_READ:
            if (resultCode == RESULT_OK) {
                boolean isHint = (requestCode == RC_HINT);
                Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
                processRetrievedCredential(credential, isHint);
            } else {
                Log.e(TAG, "Credential Read: NOT OK");
                showToast("Credential Read Failed");
            }
            
            mIsResolving = false;
            break;
        case RC_SAVE:
            if (resultCode == RESULT_OK) {
                Log.d(TAG, "Credential Save: OK");
                showToast("Credential Save Success");
            } else {
                Log.e(TAG, "Credential Save: NOT OK");
                showToast("Credential Save Failed");
            }

            mIsResolving = false;
            break;
    }
}
 
Example #20
Source File: SmartLock.java    From easygoogle with Apache License 2.0 5 votes vote down vote up
/**
 * Delete a saved Credential object from the SmartLock store.
 * @param credential the Credential to delete.
 */
public void delete(Credential credential) {
    Auth.CredentialsApi.delete(getFragment().getGoogleApiClient(), credential)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    Log.d(TAG, "delete:onResult:" + status);
                }
            });
}
 
Example #21
Source File: SmartLockHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/** Initialize saving a credential. */
public void saveCredentials(@Nullable Credential credential) {
    if (!getArguments().enableCredentials) {
        setResult(Resource.forSuccess(mResponse));
        return;
    }
    setResult(Resource.<IdpResponse>forLoading());

    if (credential == null) {
        setResult(Resource.<IdpResponse>forFailure(new FirebaseUiException(
                ErrorCodes.UNKNOWN_ERROR, "Failed to build credential.")));
        return;
    }

    deleteUnusedCredentials();
    getCredentialsClient().save(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        setResult(Resource.forSuccess(mResponse));
                    } else if (task.getException() instanceof ResolvableApiException) {
                        ResolvableApiException rae = (ResolvableApiException) task.getException();
                        setResult(Resource.<IdpResponse>forFailure(
                                new PendingIntentRequiredException(
                                        rae.getResolution(), RequestCodes.CRED_SAVE)));
                    } else {
                        Log.w(TAG, "Non-resolvable exception: " + task.getException());
                        setResult(Resource.<IdpResponse>forFailure(new FirebaseUiException(
                                ErrorCodes.UNKNOWN_ERROR,
                                "Error when saving credential.",
                                task.getException())));
                    }
                }
            });
}
 
Example #22
Source File: SignInKickstarter.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    switch (requestCode) {
        case RequestCodes.CRED_HINT:
            if (resultCode == Activity.RESULT_OK) {
                handleCredential((Credential) data.getParcelableExtra(Credential.EXTRA_KEY));
            } else {
                startAuthMethodChoice();
            }
            break;
        case RequestCodes.EMAIL_FLOW:
        case RequestCodes.AUTH_PICKER_FLOW:
        case RequestCodes.PHONE_FLOW:
        case RequestCodes.PROVIDER_FLOW:
            if (resultCode == RequestCodes.EMAIL_LINK_WRONG_DEVICE_FLOW || resultCode == RequestCodes.EMAIL_LINK_INVALID_LINK_FLOW) {
                startAuthMethodChoice();
                return;
            }
            IdpResponse response = IdpResponse.fromResultIntent(data);
            if (response == null) {
                setResult(Resource.<IdpResponse>forFailure(new UserCancellationException()));
            } else if (response.isSuccessful()) {
                setResult(Resource.forSuccess(response));
            } else if (response.getError().getErrorCode() ==
                    ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT) {
                handleMergeFailure(response);
            } else {
                setResult(Resource.<IdpResponse>forFailure(response.getError()));
            }
    }
}
 
Example #23
Source File: SecondActivity.java    From journaldev with MIT License 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_REQUEST) {
        if (resultCode == RESULT_OK) {
            showToast("Deleted");
            Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            onCredentialSuccess(credential);
        } else {
            Log.d(TAG, "Request failed");
        }
    }
}
 
Example #24
Source File: HelperActivityBase.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public void startSaveCredentials(
        FirebaseUser firebaseUser,
        IdpResponse response,
        @Nullable String password) {
    // Build credential
    String accountType = ProviderUtils.idpResponseToAccountType(response);
    Credential credential = CredentialUtils.buildCredential(
            firebaseUser, password, accountType);

    // Start the dedicated SmartLock Activity
    Intent intent = CredentialSaveActivity.createIntent(
            this, getFlowParams(), credential, response);
    startActivityForResult(intent, RequestCodes.CRED_SAVE_FLOW);
}
 
Example #25
Source File: CredentialSaveActivity.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
public static Intent createIntent(Context context,
                                  FlowParameters flowParams,
                                  Credential credential,
                                  IdpResponse response) {
    return createBaseIntent(context, CredentialSaveActivity.class, flowParams)
            .putExtra(ExtraConstants.CREDENTIAL, credential)
            .putExtra(ExtraConstants.IDP_RESPONSE, response);
}
 
Example #26
Source File: CheckPhoneHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode != RequestCodes.CRED_HINT || resultCode != Activity.RESULT_OK) { return; }

    Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
    String formattedPhone = PhoneNumberUtils.formatUsingCurrentCountry(
            credential.getId(), getApplication());
    if (formattedPhone != null) {
        setResult(Resource.forSuccess(PhoneNumberUtils.getPhoneNumber(formattedPhone)));
    }
}
 
Example #27
Source File: CredentialUtils.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/**
 * @see #buildCredential(FirebaseUser, String, String)
 */
@NonNull
public static Credential buildCredentialOrThrow(@NonNull FirebaseUser user,
                                                @Nullable String password,
                                                @Nullable String accountType) {
    Credential credential = buildCredential(user, password, accountType);
    if (credential == null) {
        throw new IllegalStateException("Unable to build credential");
    }
    return credential;
}
 
Example #28
Source File: SmartLockHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveCredentials_success() {
    mHandler.getOperation().observeForever(mResultObserver);

    when(mMockCredentials.save(any(Credential.class)))
            .thenReturn(AutoCompleteTask.<Void>forSuccess(null));

    mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null);

    verify(mResultObserver).onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));
    verify(mResultObserver).onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #29
Source File: SmartLockHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveCredentials_resolution() {
    mHandler.getOperation().observeForever(mResultObserver);

    // Mock credentials to throw an RAE
    ResolvableApiException mockRae = mock(ResolvableApiException.class);
    when(mMockCredentials.save(any(Credential.class)))
            .thenReturn(AutoCompleteTask.<Void>forFailure(mockRae));

    // Kick off save
    mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null);

    InOrder inOrder = inOrder(mResultObserver);

    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));

    // Make sure we get a resolution
    ArgumentCaptor<Resource<IdpResponse>> resolveCaptor =
            ArgumentCaptor.forClass(Resource.class);
    inOrder.verify(mResultObserver).onChanged(resolveCaptor.capture());

    // Call activity result
    PendingIntentRequiredException e =
            ((PendingIntentRequiredException) resolveCaptor.getValue().getException());
    mHandler.onActivityResult(e.getRequestCode(), Activity.RESULT_OK);

    // Make sure we get success
    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
Example #30
Source File: SmartLockHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveCredentials_failure() {
    mHandler.getOperation().observeForever(mResultObserver);

    when(mMockCredentials.save(any(Credential.class)))
            .thenReturn(AutoCompleteTask.<Void>forFailure(new Exception("FAILED")));

    mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null);

    verify(mResultObserver).onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));
    verify(mResultObserver).onChanged(argThat(ResourceMatchers.<IdpResponse>isFailure()));
}