def validate_article_existence(dynamodb, article_id, user_id=None, status=None): article_info_table = dynamodb.Table(os.environ['ARTICLE_INFO_TABLE_NAME']) article_info = article_info_table.get_item(Key={'article_id': article_id}).get('Item') if article_info is None: raise RecordNotFoundError('Record Not Found') if user_id is not None and article_info['user_id'] != user_id: raise NotAuthorizedError('Forbidden') if status is not None and article_info['status'] != status: raise RecordNotFoundError('Record Not Found') return True
def test_catch_record_not_found_error(self): lambda_impl = self.TestLambdaImpl({}, {}, self.dynamodb) lambda_impl.exec_main_proc = MagicMock( side_effect=RecordNotFoundError('not found')) response = lambda_impl.main() self.assertEqual(response['statusCode'], 404) self.assertEqual(json.loads(response['body'])['message'], 'not found')
def validate_latest_price(cls, dynamodb, article_id, price): article_info_table = dynamodb.Table(os.environ['ARTICLE_INFO_TABLE_NAME']) article_info = article_info_table.get_item(Key={'article_id': article_id}).get('Item') if article_info.get('price') is None or price != article_info['price']: raise RecordNotFoundError('Price was changed') return True
def validate_parent_comment_existence(dynamodb, comment_id): table = dynamodb.Table(os.environ['COMMENT_TABLE_NAME']) comment = table.get_item(Key={'comment_id': comment_id}).get('Item') if comment is None or comment.get('parent_id'): raise RecordNotFoundError('Record Not Found') return True
def get_validated_comment(dynamodb, comment_id): table = dynamodb.Table(os.environ['COMMENT_TABLE_NAME']) comment = table.get_item(Key={'comment_id': comment_id}).get('Item') if comment is None: raise RecordNotFoundError('Record Not Found') return comment
def validate_user_existence(dynamodb, user_id): users_table = dynamodb.Table(os.environ['USERS_TABLE_NAME']) user = users_table.get_item(Key={'user_id': user_id}).get('Item') if user is None: raise RecordNotFoundError('Record Not Found') return True
def validate_article_existence(cls, dynamodb, article_id, user_id=None, status=None, version=None, is_purchased=None): article_info_table = dynamodb.Table(os.environ['ARTICLE_INFO_TABLE_NAME']) article_info = article_info_table.get_item(Key={'article_id': article_id}).get('Item') if article_info is None: raise RecordNotFoundError('Record Not Found') if user_id is not None and article_info['user_id'] != user_id: raise NotAuthorizedError('Forbidden') if status is not None and article_info['status'] != status: raise RecordNotFoundError('Record Not Found') if version is not None and not cls.__validate_version(article_info, version): raise RecordNotFoundError('Record Not Found') if is_purchased is not None and 'price' not in article_info: raise RecordNotFoundError('Record Not Found') return True
def verify_valid_response(response, request_client_id=None): if request_client_id and response.status_code == 404: raise RecordNotFoundError( '{0} is not found.'.format(request_client_id)) if response.status_code not in [200, 201, 204]: raise Exception( 'Something went wrong when call Authlete API: {0}, {1}'.format( response.status_code, response.text))
def __validate_article_content_edit(self, article_content_edit): if article_content_edit is None: raise RecordNotFoundError('Record Not Found') required_params = ['title', 'body', 'overview'] for param in required_params: if not article_content_edit[param]: raise ValidationError("%s is required" % param)
def get_cognito_user_info(cognito, user_id): try: return cognito.admin_get_user( UserPoolId=os.environ['COGNITO_USER_POOL_ID'], Username=user_id) except ClientError as e: if e.response['Error']['Code'] == 'UserNotFoundException': raise RecordNotFoundError('Record Not Found') else: raise e
def get_private_eth_address(cognito, user_id): # user_id に紐づく private_eth_address を取得 user_info = UserUtil.get_cognito_user_info(cognito, user_id) private_eth_address = [ a for a in user_info['UserAttributes'] if a.get('Name') == 'custom:private_eth_address' ] # private_eth_address が存在しないケースは想定していないため、取得出来ない場合は例外とする if len(private_eth_address) != 1: raise RecordNotFoundError('Record Not Found: private_eth_address') return private_eth_address[0]['Value']
def get_article_content_edit_history(dynamodb, user_id, article_id, version): article_content_edit_history_table = dynamodb.Table(os.environ['ARTICLE_CONTENT_EDIT_HISTORY_TABLE_NAME']) article_content_edit_history = article_content_edit_history_table.get_item( Key={ 'user_id': user_id, 'article_edit_history_id': article_id + '_' + version } ).get('Item') if article_content_edit_history is None: raise RecordNotFoundError('Record Not Found') return article_content_edit_history
def exec_main_proc(self): users_table = self.dynamodb.Table(os.environ['USERS_TABLE_NAME']) response = users_table.get_item( Key={'user_id': self.params['user_id']}) if response.get('Item') is None: raise RecordNotFoundError('Record Not Found') return { 'statusCode': 200, 'body': json.dumps(response['Item'], cls=DecimalEncoder) }
def exec_main_proc(self): user_id = self.event['requestContext']['authorizer']['claims'][ 'cognito:username'] users_table = self.dynamodb.Table(os.environ['USERS_TABLE_NAME']) response = users_table.get_item(Key={'user_id': user_id}) if response.get('Item') is None: raise RecordNotFoundError('Record Not Found') return { 'statusCode': 200, 'body': json.dumps(response['Item'], cls=DecimalEncoder) }
def is_accessible_client(client_id, user_id): try: response = requests.get(settings.AUTHLETE_CLIENT_ENDPOINT + '/get/' + str(client_id), auth=(os.environ['AUTHLETE_API_KEY'], os.environ['AUTHLETE_API_SECRET'])) if response.status_code == 404: raise RecordNotFoundError( '{0} is not found.'.format(client_id)) except requests.exceptions.RequestException as err: raise Exception( 'Something went wrong when call Authlete API: {0}'.format(err)) developer = json.loads(response.text)['developer'] return developer == user_id
def test_already_added_user_id(self): event = { 'requestContext': { 'authorizer': { 'claims': { 'cognito:username': '******', } } } } # usersテーブルとcognitoの両方にユーザが存在する場合 with patch('me_external_provider_user_create.UserUtil') as user_mock: event['body'] = json.dumps({'user_id': 'username02'}) user_mock.get_cognito_user_info.return_value = { 'Username': '******', 'UserAttributes': {} } response = MeExternalProviderUserCreate(event=event, context="", dynamodb=dynamodb).main() self.assertEqual(response['statusCode'], 400) # usersテーブルのみにユーザが存在する場合(想定されるデータ不整合のため、そのような場合でも意図したエラーを返すことのテスト) with patch('me_external_provider_user_create.UserUtil') as user_mock: event['body'] = json.dumps({'user_id': 'username02'}) user_mock.get_cognito_user_info.side_effect = RecordNotFoundError( 'Record Not Found') response = MeExternalProviderUserCreate(event=event, context="", dynamodb=dynamodb).main() self.assertEqual(response['statusCode'], 400) # cognitoのみにユーザが存在する場合(想定されるデータ不整合のため、そのような場合でも意図したエラーを返すことのテスト) with patch('me_external_provider_user_create.UserUtil') as user_mock: event['body'] = json.dumps({'user_id': 'onlycognito'}) user_mock.get_cognito_user_info.return_value = { 'Username': '******', 'UserAttributes': {} } response = MeExternalProviderUserCreate(event=event, context="", dynamodb=dynamodb).main() self.assertEqual(response['statusCode'], 400)
def exec_main_proc(self): # 必要なパラメーターを取得する self.web3 = Web3( HTTPProvider(os.environ['PRIVATE_CHAIN_OPERATION_URL'])) address = self.web3.toChecksumAddress( os.environ['PRIVATE_CHAIN_ALIS_TOKEN_ADDRESS']) user_id = self.event['requestContext']['authorizer']['claims'][ 'cognito:username'] eoa = self.__get_user_private_eth_address(user_id) # csvファイルを生成するためのdataの格納先の生成 data_for_csv = io.StringIO() # カストディ対応前にアドレスを保持していた場合は追記 user_configuration = self.__get_user_configuration(user_id) if user_configuration is not None and user_configuration.get( 'old_private_eth_address') is not None: self.setTransferHistoryToData( address, user_configuration['old_private_eth_address'], data_for_csv) self.setMintHistoryToData( address, user_configuration['old_private_eth_address'], data_for_csv) tmp_sum_token = self.__get_sum_token(data_for_csv) # private chainからトークンのTransferとMintのデータを取得し、csvに書き込むためのデータを準備する self.setTransferHistoryToData(address, eoa, data_for_csv) self.setMintHistoryToData(address, eoa, data_for_csv, tmp_sum_token) # If the file is empty, then error will be raised if len(data_for_csv.getvalue()) == 0: raise RecordNotFoundError('Record Not Found') # 生成したデータをs3にアップロードし、生成したcsvのurlをannounce_urlとしてリターンする announce_url = self.extract_file_to_s3(user_id, data_for_csv) # ユーザーにcsvのurlを通知する self.__notification(user_id, announce_url) return {'statusCode': 200}
def test_main_ok(self): with patch('me_external_provider_user_create.UserUtil.create_external_provider_user') as create_external_mock, \ patch('me_external_provider_user_create.UserUtil.get_cognito_user_info') as get_cognito_user_mock: create_external_mock.return_value = { 'AuthenticationResult': { 'AccessToken': 'aaaaa', 'IdToken': 'bbbbb', 'RefreshToken': 'ccccc' } } get_cognito_user_mock.side_effect = RecordNotFoundError( 'Record Not Found') event = { 'body': { 'user_id': 'username01', }, 'requestContext': { 'authorizer': { 'claims': { 'cognito:username': '******', } } } } event['body'] = json.dumps(event['body']) response = MeExternalProviderUserCreate(event=event, context="", dynamodb=dynamodb).main() self.assertEqual(response['statusCode'], 200) self.assertEqual( json.loads(response['body']), { 'access_token': 'aaaaa', 'id_token': 'bbbbb', 'refresh_token': 'ccccc', 'last_auth_user': '******', 'has_user_id': True, 'status': 'login' })
def exec_main_proc(self): user_id = self.event['requestContext']['authorizer']['claims'][ 'cognito:username'] users_table = self.dynamodb.Table(os.environ['USERS_TABLE_NAME']) user = users_table.get_item(Key={'user_id': user_id}).get('Item') if user is None: raise RecordNotFoundError('Record Not Found') user_first_experience_table = self.dynamodb.Table( os.environ['USER_FIRST_EXPERIENCE_TABLE_NAME']) experience = user_first_experience_table.get_item(Key={ 'user_id': user_id }).get('Item') if experience: user.update(experience) return { 'statusCode': 200, 'body': json.dumps(user, cls=DecimalEncoder) }
def test_already_exist_user_id(self): with patch('me_external_provider_user_create.UserUtil') as user_mock: event = { 'body': { 'user_id': 'existname', }, 'requestContext': { 'authorizer': { 'claims': { 'cognito:username': '******', } } } } event['body'] = json.dumps(event['body']) user_mock.get_cognito_user_info.side_effect = RecordNotFoundError( 'Record Not Found') response = MeExternalProviderUserCreate(event=event, context="", dynamodb=dynamodb).main() self.assertEqual(response['statusCode'], 400)