Пример #1
0
def reset_password_forced(email, old_password, new_password):
    """
    Change the user's password if user is in forced password change state
    """

    client = get_boto_client('cognito-idp')

    # try to authenticate and see if cognito responds with new password challenge
    try:
        response = client.admin_initiate_auth(
            UserPoolId=settings.COGNITO_USER_POOL_ID,
            ClientId=settings.COGNITO_APP_ID,
            AuthFlow='ADMIN_NO_SRP_AUTH',
            AuthParameters={
                'USERNAME': email,
                'PASSWORD': old_password
            })
    except client.exceptions.NotAuthorizedException:
        raise exceptions.NotAuthorizedException
    except client.exceptions.UserNotConfirmedException:
        raise exceptions.UserNotConfirmedException
    except client.exceptions.UserNotFoundException:
        raise exceptions.UserNotFoundException

    # change password as admin - user has already proven they know old password
    if response.get('ChallengeName') == 'NEW_PASSWORD_REQUIRED':
        try:
            client.admin_set_user_password(
                UserPoolId=settings.COGNITO_USER_POOL_ID,
                Username=email,
                Password=new_password,
                Permanent=True)
        except ParamValidationError:
            raise exceptions.ParamValidationError
Пример #2
0
def create_sub_user(email):

    client = get_boto_client('cognito-idp')

    temp_password = create_temp_password()

    try:
        response = client.admin_create_user(
            UserPoolId=settings.COGNITO_USER_POOL_ID,
            Username=email,
            UserAttributes=[{
                'Name': 'email',
                'Value': email
            }],
            TemporaryPassword=temp_password,
            DesiredDeliveryMediums=['EMAIL'])
    except client.exceptions.UsernameExistsException:
        raise exceptions.UsernameExistsException
    else:

        # when ready, use this method below instead
        #attrs = {a['Name']: a['Value'] for a in response['User']['Attributes']}
        #return attrs.get('sub')

        # TODO: clean this up
        for attr in response['User']['Attributes']:
            if attr['Name'] == 'sub':
                return attr['Value']
Пример #3
0
def create_user(email, password, registration_method="email"):

    # using this to add superusers as well, with registration "superuser", lambda checks this

    client = get_boto_client('cognito-idp')

    try:
        response = client.sign_up(ClientId=settings.COGNITO_APP_ID,
                                  Username=email,
                                  Password=password,
                                  UserAttributes=[{
                                      'Name': 'email',
                                      'Value': email
                                  }],
                                  ValidationData=[
                                      {
                                          'Name': 'registration_method',
                                          'Value': registration_method
                                      },
                                  ])
    except ParamValidationError:
        raise exceptions.ParamValidationError
    except client.exceptions.InvalidParameterException:
        raise exceptions.InvalidParameterException
    except client.exceptions.UsernameExistsException:
        raise exceptions.UsernameExistsException
    else:
        return response.get('UserSub')
Пример #4
0
def sign_in_user(email, password):

    client = get_boto_client('cognito-idp')

    try:
        response = client.admin_initiate_auth(
            UserPoolId=settings.COGNITO_USER_POOL_ID,
            ClientId=settings.COGNITO_APP_ID,
            AuthFlow='ADMIN_NO_SRP_AUTH', # must configure app client
            AuthParameters={
                'USERNAME': email,
                'PASSWORD': password
            }
        )
    except client.exceptions.NotAuthorizedException:
        raise exceptions.NotAuthorizedException
    except client.exceptions.UserNotConfirmedException:
        raise exceptions.UserNotConfirmedException
    except client.exceptions.UserNotFoundException:
        raise exceptions.UserNotFoundException

    # check if password change required
    if response.get('ChallengeName') == 'NEW_PASSWORD_REQUIRED':
        raise exceptions.NewPasswordRequiredError

    return {
        'access_token': response['AuthenticationResult']['AccessToken'],
        'refresh_token': response['AuthenticationResult']['RefreshToken'],
        'id_token': response['AuthenticationResult']['IdToken']
    }
Пример #5
0
def get_presigned_url(object_key, bucket, expiration_secs):

    client = get_boto_client('s3')

    url = client.generate_presigned_url('get_object', Params={'Bucket': bucket, 'Key': object_key},
                                        ExpiresIn=expiration_secs)
    return url
Пример #6
0
def put_firehose_record(payload, stream_name):

    # newline is the record deliminator so remove it from inside the record
    data = json.dumps(payload).replace('\n', '')

    client = get_boto_client('firehose')
    client.put_record(DeliveryStreamName=stream_name,
                      Record={'Data': data + '\n'})
Пример #7
0
def delete_cloudwatch_rule(rule_name):

    if rule_name is None:
        return

    client = get_boto_client('events')
    client.remove_targets(Rule=rule_name, Ids=["1"])
    client.delete_rule(Name=rule_name)
Пример #8
0
def get_global_config():

    client = get_boto_client('dynamodb')

    data = client.scan(TableName=settings.DYNAMO_CONFIG_TABLE_NAME, )

    items = dynamodb_json_util.loads(data['Items'])
    config = {item['name']: item['value'] for item in items}
    return config
Пример #9
0
def verify_user_attribute(attribute, code, access_token):

    client = get_boto_client('cognito-idp')

    try:
        client.verify_user_attribute(AccessToken=access_token,
                                     AttributeName=attribute,
                                     Code=code)
    except client.exceptions.CodeMismatchException:
        raise exceptions.CodeMismatchException
Пример #10
0
def update_account(email, attrs):

    client = get_boto_client('cognito-idp')
    try:
        client.admin_update_user_attributes(
            UserPoolId=settings.COGNITO_USER_POOL_ID,
            Username=email,
            UserAttributes=attrs)
    except client.exceptions.AliasExistsException:
        raise exceptions.AliasExistsException
Пример #11
0
def verify_email(email):

    client = get_boto_client('cognito-idp')
    client.admin_update_user_attributes(
        UserPoolId=settings.COGNITO_USER_POOL_ID,
        Username=email,
        UserAttributes=[
            {
                'Name': 'email_verified',
                'Value': 'true'
            },
        ])
Пример #12
0
def get_is_email_verified(email):

    client = get_boto_client('cognito-idp')

    cognito_response = client.admin_get_user(
        UserPoolId=settings.COGNITO_USER_POOL_ID, Username=email)

    for attr in cognito_response['UserAttributes']:
        if attr['Name'] == 'email_verified':
            return attr['Value'] == 'true'

    return False
Пример #13
0
def get_dynamodb_credentials(short_name):

    client = get_boto_client('dynamodb')

    item = client.get_item(TableName=settings.S3_USER_CREDENTIALS_TABLE,
                           Key={'organization': {
                               'S': short_name
                           }})

    print(short_name)
    print(item)

    item = dynamodb_json_util.loads(item)['Item']
    return item['credentials']
Пример #14
0
def change_password(old_password, new_password, access_token):

    client = get_boto_client('cognito-idp')

    try:
        client.change_password(PreviousPassword=old_password,
                               ProposedPassword=new_password,
                               AccessToken=access_token)
    except client.exceptions.NotAuthorizedException:
        raise exceptions.NotAuthorizedException
    except client.exceptions.LimitExceededException:
        raise exceptions.LimitExceededException
    except ParamValidationError:
        raise exceptions.ParamValidationError
Пример #15
0
def refresh_access_token(refresh_token):

    client = get_boto_client('cognito-idp')

    try:
        response = client.initiate_auth(ClientId=settings.COGNITO_APP_ID,
                                        AuthFlow='REFRESH_TOKEN_AUTH',
                                        AuthParameters={
                                            'REFRESH_TOKEN': refresh_token,
                                        })
    except client.exceptions.NotAuthorizedException:
        raise exceptions.NotAuthorizedException

    return response['AuthenticationResult'][
        'AccessToken']  # fixme: is this safe?
Пример #16
0
def delete_all_users():
    assert settings.STAGE != 'production'

    client = get_boto_client('cognito-idp')
    response = client.list_users(
        UserPoolId=settings.COGNITO_USER_POOL_ID,
        AttributesToGet=[
            'email',
        ],
    )
    users = response['Users']
    print("...removing %d Cognito users" % (len(users)))
    for user in users:
        sub = user['Username']
        client.admin_delete_user(UserPoolId=settings.COGNITO_USER_POOL_ID,
                                 Username=sub)
Пример #17
0
def get_files(prefix, suffix, bucket_name):

    s3_client = get_boto_client('s3')

    response = s3_client.list_objects(
        Bucket=bucket_name,
        EncodingType='url',
        Prefix=prefix
    )

    is_truncated = response['IsTruncated']
    next_marker = response.get('NextMarker') # if is_truncated, use next_marker
    contents = response.get('Contents', None)
    if contents is not None:
        objects = [c['Key'] for c in contents if c['Key'].endswith(suffix)]
        return objects
    else:
        return []
Пример #18
0
def reset_password_start(email):
    """
    Start the password reset flow - sends an email to the user
    """

    client = get_boto_client('cognito-idp')

    try:
        client.forgot_password(ClientId=settings.COGNITO_APP_ID,
                               Username=email)
    except client.exceptions.NotAuthorizedException:
        raise exceptions.NotAuthorizedException
    except client.exceptions.InvalidParameterException:
        raise exceptions.InvalidParameterException
    except client.exceptions.LimitExceededException:
        raise exceptions.LimitExceededException
    except client.exceptions.UserNotFoundException:
        raise exceptions.UserNotFoundException
Пример #19
0
def create_dynamodb_credentials(org_short_name, username, password,
                                permissions):
    assert isinstance(permissions, list)

    client = get_boto_client('dynamodb')
    item = {
        'organization': org_short_name,
        'credentials': [{
            'p': password,
            'u': username,
            'permissions': permissions
        }]
    }

    dynamodb_json = dynamodb_json_util.dumps(item)
    dynamodb_json = json.loads(dynamodb_json)

    client.put_item(TableName=settings.S3_USER_CREDENTIALS_TABLE,
                    Item=dynamodb_json)
Пример #20
0
def delete_testing_users():
    # remove testing users that start with a digit
    client = get_boto_client('cognito-idp')
    response = client.list_users(
        UserPoolId=settings.COGNITO_USER_POOL_ID,
        AttributesToGet=[
            'email',
        ],
    )
    users = response['Users']
    print("...retrieving %d Cognito users" % (len(users)))
    for user in users:
        for attr in user['Attributes']:
            if attr['Name'] == 'email' and attr['Value'][0].isdigit():
                print("...removing %s" % attr['Value'])
                sub = user['Username']
                client.admin_delete_user(
                    UserPoolId=settings.COGNITO_USER_POOL_ID, Username=sub)
                break
Пример #21
0
def reset_password_confirm(email, code, password):
    """
    Complete the password reset flow - use code and new password to change
    """

    client = get_boto_client('cognito-idp')

    try:
        client.confirm_forgot_password(ClientId=settings.COGNITO_APP_ID,
                                       Username=email,
                                       ConfirmationCode=code,
                                       Password=password)
    except client.exceptions.CodeMismatchException:
        raise exceptions.CodeMismatchException
    except client.exceptions.ExpiredCodeException:
        raise exceptions.ExpiredCodeException
    except client.exceptions.UserNotFoundException:
        raise exceptions.UserNotFoundException
    except ParamValidationError:
        raise exceptions.ParamValidationError
Пример #22
0
def put_s3_item(body, bucket, object_key):

    client = get_boto_client('s3')
    client.put_object(Body=body, Bucket=bucket, Key=object_key)
Пример #23
0
def confirm_account(email):

    client = get_boto_client('cognito-idp')

    client.admin_confirm_sign_up(UserPoolId=settings.COGNITO_USER_POOL_ID,
                                 Username=email)
Пример #24
0
def sign_out_user(email):

    client = get_boto_client('cognito-idp')
    client.admin_user_global_sign_out(UserPoolId=settings.COGNITO_USER_POOL_ID,
                                      Username=email)