Example #1
0
def get(request):
    if not request.event["cognitoIdentityId"]:
        raise errors.ForbiddenRequestError('The credentials used did not contain Cognito identity information')

    account = account_utils.get_account_for_identity(request.event["cognitoIdentityId"])
    if not account:
        raise errors.ClientError("No account found for '{}'".format(request.event["cognitoIdentityId"]))

    if account.get('AccountBlacklisted'):
        raise errors.ForbiddenRequestError('The account is blacklisted')

    response = account_utils.get_account_table().get_item(Key = { 'AccountId': account['AccountId'] }, ConsistentRead = False)

    if not 'Item' in response:
        raise errors.ClientError("No account found for '{}'".format(account['AccountId']))

    return account_utils.convert_account_from_dynamo_to_player_model(response['Item'])
Example #2
0
def put(request, UpdateAccountRequest):
    if not request.event["cognitoIdentityId"]:
        raise errors.ForbiddenRequestError(
            'The credentials used did not contain Cognito identity information'
        )

    account_utils.validate_account_update_request(UpdateAccountRequest)

    account = account_utils.get_account_for_identity(
        request.event["cognitoIdentityId"])

    if not account:
        account = {
            'AccountId': str(uuid.uuid4()),
            'CognitoIdentityId': request.event["cognitoIdentityId"]
        }

        if 'PlayerName' in UpdateAccountRequest:
            # IndexedPlayerName and PlayerNameSortKey are used to search accounts by name, case insensitive.  See accountsearch.py
            account['PlayerName'] = UpdateAccountRequest['PlayerName']
            account['IndexedPlayerName'] = UpdateAccountRequest[
                'PlayerName'].lower()
            account['PlayerNameSortKey'] = randint(
                1, account_utils.get_name_sort_key_count())

        account_utils.create_account(account)
        return account_utils.convert_account_from_dynamo_to_player_model(
            account)
    else:
        if account.get('AccountBlacklisted'):
            raise errors.ForbiddenRequestError('The account is blacklisted')

        updateRequest = {'AccountId': account['AccountId']}

        if 'PlayerName' in UpdateAccountRequest:
            # IndexedPlayerName and PlayerNameSortKey are used to search accounts by name, case insensitive.  See accountsearch.py
            updateRequest['PlayerName'] = UpdateAccountRequest['PlayerName']
            updateRequest['IndexedPlayerName'] = UpdateAccountRequest[
                'PlayerName'].lower()
            updateRequest['PlayerNameSortKey'] = randint(
                1, account_utils.get_name_sort_key_count())

        result = account_utils.update_account(updateRequest)
        return account_utils.convert_account_from_dynamo_to_player_model(
            result)
Example #3
0
def get_player_account(cog_id):
    return account_utils.get_account_for_identity(cog_id)
Example #4
0
def get(request, cog_id):
    account = account_utils.get_account_for_identity(cog_id)
    return account
Example #5
0
def verify_auth_challenge_response(event):
    if 'privateChallengeParameters' not in event['request'] or 'type' not in event['request']['privateChallengeParameters']:
        print 'The request is missing privateChallengeParameters.type'
        event['response']['answerCorrect'] = False
        return

    challenge_type = event['request']['privateChallengeParameters']['type']
    password = None
    new_password = None
    if challenge_type == 'BasicAuth':
        password = event['request']['challengeAnswer']
    elif challenge_type == 'ForceChangePassword':
        try:
            answer = json.loads(event['request']['challengeAnswer'])
        except ValueError as e:
            print 'Unable to parse the answer for ForceChangePassword as json'
            event['response']['answerCorrect'] = False
            return

        password = answer.get('password')
        new_password = answer.get('newPassword')
        if password == None or new_password == None:
            print 'The answer for the ForceChangePassword challenge is missing the password or newPassword.'
            event['response']['answerCorrect'] = False
            return
    else:
        print 'Unsupported challenge type: {}'.format(challenge_type)
        event['response']['answerCorrect'] = False
        return

    # Use the provided username and password to attempt authentication using the admin API.
    try:
        idpResponse = account_utils.get_user_pool_client().admin_initiate_auth(
            UserPoolId = event['userPoolId'],
            ClientId = event['callerContext']['clientId'],
            AuthFlow = 'ADMIN_NO_SRP_AUTH',
            AuthParameters = {
                'USERNAME': event['userName'],
                'PASSWORD': password
            }
        )
    except:
        traceback.print_exc()
        raise errors.ClientError("Authentication failed")

    if 'AuthenticationResult' not in idpResponse:
        if 'ChallengeName' in idpResponse:
            print 'The response from AdminInitiateAuth contained a {} challenge.'.format(idpResponse.get('ChallengeName'))

        if idpResponse.get('ChallengeName') == 'NEW_PASSWORD_REQUIRED':
            idpResponse = account_utils.get_user_pool_client().admin_respond_to_auth_challenge(
                UserPoolId=event['userPoolId'],
                ClientId=event['callerContext']['clientId'],
                ChallengeName='NEW_PASSWORD_REQUIRED',
                ChallengeResponses={
                    'NEW_PASSWORD': new_password,
                    'USERNAME': event['userName']
                },
                Session=idpResponse['Session']
            )

            if 'AuthenticationResult' not in idpResponse:
                if 'ChallengeName' in idpResponse:
                    print 'The response from AdminInitiateAuth contained a {} challenge.'.format(idpResponse.get('ChallengeName'))
                print 'Authentication failed: the response from AdminInitiateAuth did not contain AuthenticationResult'
                event['response']['answerCorrect'] = False
                return
        else:
            print 'Authentication failed: the response from AdminInitiateAuth did not contain AuthenticationResult'
            event['response']['answerCorrect'] = False
            return

    if 'IdToken' not in idpResponse['AuthenticationResult']:
        print 'The response from AdminInitiateAuth did not contain an IdToken'
        event['response']['answerCorrect'] = False
        return

    # Use the token to get the identity for the user.
    provider_id = 'cognito-idp.' + event['region'] + '.amazonaws.com/' + event['userPoolId']
    idResponse = account_utils.get_identity_pool_client().get_id(
        IdentityPoolId = account_utils.get_identity_pool_id(),
        Logins = {
            provider_id: idpResponse['AuthenticationResult']['IdToken']
        }
    )

    if 'IdentityId' not in idResponse:
        print 'The response from GetId did not contain an IdentityId'
        event['response']['answerCorrect'] = False
        return

    # Update the identity to username mapping.
    account = account_utils.get_account_for_identity(idResponse['IdentityId'])
    if account:
        if account.get('AccountBlacklisted'):
            raise errors.ClientError("Authentication failed: the account is blacklisted")

        account_utils.update_account({
             'AccountId': account['AccountId'],
             'CognitoIdentityId': idResponse['IdentityId'],
             'CognitoUsername': event['userName']
        })
    else:
        account_utils.create_account({
             'AccountId': str(uuid.uuid4()),
             'CognitoIdentityId': idResponse['IdentityId'],
             'CognitoUsername': event['userName']
        })

    event['response']['answerCorrect'] = True