Search in sources :

Example 1 with CognitoDevice

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice in project aws-sdk-android by aws-amplify.

the class OAuth2Utils method _signIn.

private Runnable _signIn(final String username, final String password, final Map<String, String> validationData, final Map<String, String> clientMetadata, final AuthFlowType authFlowType, final Callback<SignInResult> callback) {
    this.signInCallback = callback;
    signInState = null;
    mStore.set(SIGN_IN_MODE, SignInMode.SIGN_IN.toString());
    return new Runnable() {

        @Override
        public void run() {
            try {
                userpool.getUser(username).getSession(clientMetadata, new AuthenticationHandler() {

                    @Override
                    public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
                        try {
                            mCognitoUserSession = userSession;
                            signInState = SignInState.DONE;
                        } catch (Exception e) {
                            signInCallback.onError(e);
                            signInCallback = null;
                        }
                        try {
                            if (isFederationEnabled()) {
                                federatedSignInWithoutAssigningState(userpoolsLoginKey, mCognitoUserSession.getIdToken().getJWTToken());
                            }
                            releaseSignInWait();
                        } catch (Exception e) {
                            Log.w(TAG, "Failed to federate tokens during sign-in", e);
                        } finally {
                            setUserState(new UserStateDetails(UserState.SIGNED_IN, getSignInDetailsMap()));
                        }
                        signInCallback.onResult(SignInResult.DONE);
                    }

                    @Override
                    public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
                        Log.d(TAG, "Sending password.");
                        final HashMap<String, String> authParameters = new HashMap<>();
                        // Check if the auth flow type setting is in the configuration.
                        boolean authFlowTypeInConfig = awsConfiguration.optJsonObject(AUTH_KEY) != null && awsConfiguration.optJsonObject(AUTH_KEY).has("authenticationFlowType");
                        try {
                            String resolvedAuthFlowType = authFlowType != null ? authFlowType.name() : null;
                            if (resolvedAuthFlowType == null && authFlowTypeInConfig) {
                                resolvedAuthFlowType = awsConfiguration.optJsonObject(AUTH_KEY).getString("authenticationFlowType");
                            }
                            if (resolvedAuthFlowType != null && AUTH_TYPE_INIT_CUSTOM_AUTH.equals(resolvedAuthFlowType)) {
                                // use one of the below constructors depending on what's passed in.
                                if (password != null) {
                                    authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, password, authParameters, validationData));
                                } else {
                                    authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, authParameters, validationData));
                                }
                            } else if (resolvedAuthFlowType != null && AUTH_TYPE_INIT_USER_PASSWORD.equals(resolvedAuthFlowType)) {
                                // If there's a value in the config and it's USER_PASSWORD_AUTH, set the auth type (challenge name)
                                // to be USER_PASSWORD.
                                AuthenticationDetails authenticationDetails = new AuthenticationDetails(username, password, validationData);
                                authenticationDetails.setAuthenticationType(CHLG_TYPE_USER_PASSWORD);
                                authenticationContinuation.setAuthenticationDetails(authenticationDetails);
                            } else {
                                // Otherwise, auth flow is USER_SRP_AUTH and the auth type (challenge name)
                                // will default to PASSWORD_VERIFIER.
                                Log.d(TAG, "Using USER_SRP_AUTH for flow type.");
                                authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, password, validationData));
                            }
                        } catch (JSONException exception) {
                            Log.w(TAG, "Exception while attempting to read authenticationFlowType from config.", exception);
                        }
                        authenticationContinuation.continueTask();
                    }

                    @Override
                    public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
                        signInMfaContinuation = continuation;
                        CognitoUserCodeDeliveryDetails parameters = continuation.getParameters();
                        signInState = SignInState.SMS_MFA;
                        signInCallback.onResult(new SignInResult(SignInState.SMS_MFA, new UserCodeDeliveryDetails(parameters.getDestination(), parameters.getDeliveryMedium(), parameters.getAttributeName())));
                    }

                    @Override
                    public void authenticationChallenge(ChallengeContinuation continuation) {
                        try {
                            signInState = SignInState.valueOf(continuation.getChallengeName());
                            signInChallengeContinuation = continuation;
                            signInCallback.onResult(new SignInResult(signInState, continuation.getParameters()));
                        } catch (IllegalArgumentException e) {
                            signInCallback.onError(e);
                        }
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        signInCallback.onError(exception);
                    }
                });
            } catch (Exception e) {
                callback.onError(e);
            }
        }
    };
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) CognitoUserCodeDeliveryDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails) UserCodeDeliveryDetails(com.amazonaws.mobile.client.results.UserCodeDeliveryDetails) JSONException(org.json.JSONException) JSONException(org.json.JSONException) InvalidUserPoolConfigurationException(com.amazonaws.services.cognitoidentityprovider.model.InvalidUserPoolConfigurationException) AmazonClientException(com.amazonaws.AmazonClientException) NotAuthorizedException(com.amazonaws.services.cognitoidentity.model.NotAuthorizedException) SignInResult(com.amazonaws.mobile.client.results.SignInResult) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) CognitoUserCodeDeliveryDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) ReturningRunnable(com.amazonaws.mobile.client.internal.ReturningRunnable) ChallengeContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CognitoUserSession(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession) AuthenticationDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails)

Example 2 with CognitoDevice

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice in project aws-sdk-android by aws-amplify.

the class AWSMobileClientTest method testRevokeTokenWithSignedOutUser.

@Test
public void testRevokeTokenWithSignedOutUser() throws Exception {
    auth.signIn(username, PASSWORD, null);
    assertTrue("isSignedIn is true", auth.isSignedIn());
    final CountDownLatch revokeTokenLatch = new CountDownLatch(1);
    final CognitoUser user = userPool.getCurrentUser();
    user.getSession(new AuthenticationHandler() {

        @Override
        public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
            revokeTokenLatch.countDown();
        }

        @Override
        public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
        }

        @Override
        public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
        }

        @Override
        public void authenticationChallenge(ChallengeContinuation continuation) {
        }

        @Override
        public void onFailure(Exception exception) {
            exception.printStackTrace();
            fail("Sign in failed.");
        }
    });
    revokeTokenLatch.await(5, TimeUnit.SECONDS);
    auth.signOut();
    assertFalse("isSignedIn is false", auth.isSignedIn());
    try {
        user.revokeTokens();
    } catch (Exception e) {
        assertTrue(e instanceof InvalidParameterException);
    }
}
Also used : MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) InvalidParameterException(com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) ChallengeContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CountDownLatch(java.util.concurrent.CountDownLatch) CognitoUserSession(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession) CognitoUser(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser) UsernameExistsException(com.amazonaws.services.cognitoidentityprovider.model.UsernameExistsException) JSONException(org.json.JSONException) UserNotConfirmedException(com.amazonaws.services.cognitoidentityprovider.model.UserNotConfirmedException) NotAuthorizedException(com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException) ResourceNotFoundException(com.amazonaws.services.cognitoidentityprovider.model.ResourceNotFoundException) InvalidParameterException(com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException) Test(org.junit.Test)

Example 3 with CognitoDevice

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice in project aws-sdk-android by aws-amplify.

the class DeviceOperations method _getDevice.

private ReturningRunnable<Device> _getDevice(final String deviceKey) {
    return new ReturningRunnable<Device>() {

        @Override
        public Device run() throws Exception {
            CognitoDevice cognitoDevice = getCognitoDevice(deviceKey);
            final GetDeviceRequest getDeviceRequest = new GetDeviceRequest();
            getDeviceRequest.setAccessToken(mobileClient.getTokens().getAccessToken().getTokenString());
            getDeviceRequest.setDeviceKey(cognitoDevice.getDeviceKey());
            final GetDeviceResult getDeviceResult = userpoolLL.getDevice(getDeviceRequest);
            return marshallDeviceTypeToDevice(getDeviceResult.getDevice());
        }
    };
}
Also used : ReturningRunnable(com.amazonaws.mobile.client.internal.ReturningRunnable) GetDeviceRequest(com.amazonaws.services.cognitoidentityprovider.model.GetDeviceRequest) GetDeviceResult(com.amazonaws.services.cognitoidentityprovider.model.GetDeviceResult) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice)

Example 4 with CognitoDevice

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice in project aws-sdk-android by aws-amplify.

the class DeviceOperations method _rememberDevice.

private ReturningRunnable<Void> _rememberDevice(final String deviceKey, final boolean rememberDevice) {
    return new ReturningRunnable<Void>() {

        @Override
        public Void run() throws Exception {
            CognitoDevice cognitoDevice = getCognitoDevice(deviceKey);
            final UpdateDeviceStatusRequest updateDeviceStatusRequest = new UpdateDeviceStatusRequest().withAccessToken(mobileClient.getTokens().getAccessToken().getTokenString()).withDeviceKey(cognitoDevice.getDeviceKey()).withDeviceRememberedStatus(rememberDevice ? DeviceRememberedStatusType.Remembered : DeviceRememberedStatusType.Not_remembered);
            userpoolLL.updateDeviceStatus(updateDeviceStatusRequest);
            return null;
        }
    };
}
Also used : ReturningRunnable(com.amazonaws.mobile.client.internal.ReturningRunnable) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) UpdateDeviceStatusRequest(com.amazonaws.services.cognitoidentityprovider.model.UpdateDeviceStatusRequest)

Example 5 with CognitoDevice

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice in project aws-sdk-android by aws-amplify.

the class CognitoIdentityProviderDevicesTest method listDevicesInCurrentThread.

@Test
public void listDevicesInCurrentThread() {
    // Set mock result for the change password request API call
    doReturn(TEST_VALID_LIST_DEVICES_RESPONSE).when(mockCSIClient).listDevices(any(ListDevicesRequest.class));
    // Store tokens in shared preferences
    awsKeyValueStorageUtility.put("CognitoIdentityProvider." + TEST_CLIENT_ID + "." + TEST_USER_NAME + "." + ".idToken", getValidJWT(3600L));
    awsKeyValueStorageUtility.put("CognitoIdentityProvider." + TEST_CLIENT_ID + "." + TEST_USER_NAME + "." + "accessToken", getValidJWT(3600L));
    awsKeyValueStorageUtility.put("CognitoIdentityProvider." + TEST_CLIENT_ID + "." + TEST_USER_NAME + "." + "refreshToken", TEST_CACHED_RTOKEN);
    testUser.listDevices(10, "ptoken", new DevicesHandler() {

        @Override
        public void onSuccess(List<CognitoDevice> devices) {
            assertNotNull(devices);
            ArgumentCaptor<ListDevicesRequest> argumentCaptor = ArgumentCaptor.forClass(ListDevicesRequest.class);
            verify(mockCSIClient).listDevices(argumentCaptor.capture());
            ListDevicesRequest requestSent = argumentCaptor.getValue();
            assertEquals("ptoken", requestSent.getPaginationToken());
        }

        @Override
        public void onFailure(Exception exception) {
            assertNotNull(exception);
        }
    });
}
Also used : DevicesHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.DevicesHandler) ArgumentCaptor(org.mockito.ArgumentCaptor) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) ListDevicesRequest(com.amazonaws.services.cognitoidentityprovider.model.ListDevicesRequest) Test(org.junit.Test)

Aggregations

CognitoDevice (com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice)22 Test (org.junit.Test)15 ArgumentCaptor (org.mockito.ArgumentCaptor)12 CognitoUserSession (com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession)10 AuthenticationContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation)10 ChallengeContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation)10 MultiFactorAuthenticationContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation)10 AuthenticationHandler (com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler)10 AuthenticationDetails (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails)7 GenericHandler (com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler)6 HashMap (java.util.HashMap)6 ReturningRunnable (com.amazonaws.mobile.client.internal.ReturningRunnable)5 FlowTracker (com.amazonaws.mobileconnectors.cognitoidentityprovider.utils.FlowTracker)4 InitiateAuthRequest (com.amazonaws.services.cognitoidentityprovider.model.InitiateAuthRequest)4 Map (java.util.Map)4 JSONException (org.json.JSONException)4 Ignore (org.junit.Ignore)4 SignInResult (com.amazonaws.mobile.client.results.SignInResult)3 ForgetDeviceRequest (com.amazonaws.services.cognitoidentityprovider.model.ForgetDeviceRequest)3 GetDeviceRequest (com.amazonaws.services.cognitoidentityprovider.model.GetDeviceRequest)3