Пример #1
0
def initiate(event, context):
    logger.info("Received request for initiate payment")
    try:
        payload = json.loads(event['body'])
        path_parameters = event["pathParameters"]
        if validate_dict(payload, ["price", "payment_method"]) \
            and validate_dict(path_parameters, ["order_id"]):
            order_id = path_parameters["order_id"]
            amount = payload["price"]["amount"]
            currency = payload["price"]["currency"]
            payment_method = payload["payment_method"]
            logger.info(f"Fetched values from request\n"
                        f"order_id: {order_id}\n"
                        f"amount: {amount} {currency}\n"
                        f"payment_method: {payment_method}")
            response = OrderManager().initiate_payment_against_order(order_id, amount, currency, payment_method)
            status_code = StatusCode.CREATED
        else:
            status_code = StatusCode.BAD_REQUEST
            response = "Bad Request"
            logger.error(response)
            logger.info(event)
    except Exception as e:
        logger.info(event)
        response = "Failed to initiate payment"
        logger.error(response)
        logger.error(e)
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(f"got error : {response} \n {str(e)} \n for event : {event} ", SLACK_HOOK)
    return generate_lambda_response(
        status_code=status_code,
        message=response
    )
Пример #2
0
def execute(event, context):
    logger.info("Received request to execute payment")
    try:
        payload = json.loads(event['body'])
        path_parameters = event["pathParameters"]
        if validate_dict(payload, ["payment_method", "payment_details"]) \
            and validate_dict(path_parameters, ["order_id", "payment_id"]):
            order_id = path_parameters["order_id"]
            payment_id = path_parameters["payment_id"]
            payment_method = payload["payment_method"]
            payment_details = payload["payment_details"]
            logger.info(f"Fetched values from the request,"
                        f"order_id: {order_id}\n"
                        f"payment_id: {payment_id}\n"
                        f"payment_method: {payment_method}\n"
                        f"payment_details: {payment_details}")
            response = OrderManager().execute_payment_against_order(
                order_id, payment_id, payment_details, payment_method)
            status_code = StatusCode.CREATED
        else:
            status_code = StatusCode.BAD_REQUEST
            response = "Bad Request"
            logger.error(response)
            logger.info(event)
    except Exception as e:
        response = "Failed to execute payment"
        logger.error(response)
        logger.info(event)
        logger.error(e)
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(
            "ERROR",
            f"got error : {response} \n {str(e)} \n for event : {event} ",
            SLACK_HOOK)
    return generate_lambda_response(status_code=status_code, message=response)
Пример #3
0
def cancel(event, context):
    logger.info("Received request to cancel payment")
    try:
        path_parameters = event["pathParameters"]
        if validate_dict(path_parameters, ["order_id", "payment_id"]):
            order_id = path_parameters["order_id"]
            payment_id = path_parameters["payment_id"]
            response = OrderManager().cancel_payment_against_order(order_id, payment_id)
            status_code = StatusCode.CREATED
        else:
            status_code = StatusCode.BAD_REQUEST
            response = "Bad Request"
            logger.error(response)
            logger.info(event)
    except Exception as e:
        response = "Failed to cancel payment"
        logger.error(response)
        logger.info(event)
        logger.error(e)
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(f"got error : {response} \n {str(e)} \n for event : {event} ", SLACK_HOOK)
    return generate_lambda_response(
        status_code=status_code,
        message=response
    )
Пример #4
0
def get_daemon_config_for_current_network(event, context):
    logger.info(f"event for get_daemon_config_for_current_network:: {event}")
    username = event["requestContext"]["authorizer"]["claims"]["email"]
    path_parameters = event["pathParameters"]
    query_parameters = event["queryStringParameters"]
    if not validate_dict(path_parameters,
                         ["org_uuid", "service_uuid", "group_id"
                          ]) or 'network' not in query_parameters:
        raise BadRequestException()
    org_uuid = path_parameters["org_uuid"]
    service_uuid = path_parameters["service_uuid"]
    group_id = path_parameters["group_id"]
    if query_parameters["network"] == EnvironmentType.TEST.value:
        response = ServicePublisherService(
            username, org_uuid,
            service_uuid).daemon_config(environment=EnvironmentType.TEST.value)
    elif query_parameters["network"] == EnvironmentType.MAIN.value:
        response = ServicePublisherService(
            username, org_uuid,
            service_uuid).daemon_config(environment=EnvironmentType.MAIN.value)
    else:
        raise EnvironmentNotFoundException()
    return generate_lambda_response(StatusCode.OK, {
        "status": "success",
        "data": response,
        "error": {}
    },
                                    cors_enabled=True)
def create(event, context):
    logger.info("Received request to create order")
    try:
        payload = json.loads(event['body'])
        if validate_dict(payload, ["price", "username"]):
            amount = payload["price"]["amount"]
            currency = payload["price"]["currency"]
            username = payload["username"]
            item_details = payload["item_details"]
            logger.info(f"Fetched values from request\n"
                        f"username: {username}\n"
                        f"amount: {amount} {currency}\n"
                        f"item_details: {item_details}")
            response = OrderManager().create_order(amount, currency,
                                                   item_details, username)
            status_code = StatusCode.CREATED
        else:
            status_code = StatusCode.BAD_REQUEST
            response = "Bad Request"
            logger.error(response)
            logger.info(event)
    except Exception as e:
        response = "Failed to create order"
        logger.error(response)
        logger.info(event)
        logger.error(e)
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(
            f"got error : {response} \n {str(e)} \n for event : {event} ",
            SLACK_HOOK)
    return generate_lambda_response(status_code=status_code, message=response)
 def test_get_wallets(self, invoke_lambda_mock):
     invoke_lambda_mock.return_value = {
         "statusCode":
         200,
         "body":
         json.dumps({
             "status": "success",
             "data": {
                 "username":
                 "******",
                 "wallets": [{
                     "address": "0x123",
                     "is_default": 1,
                     "type": "GENERAL",
                     "status": 0
                 }]
             },
         })
     }
     username = "******"
     wallet_required_keys = ["address", "is_default", "type", "status"]
     wallets = WalletService().get_wallets(username)
     assert isinstance(wallets, dict)
     assert "username" in wallets
     assert "wallets" in wallets
     if len(wallets["wallets"]) > 0:
         wallet_details = wallets["wallets"][0]
         assert validate_dict(wallet_details, wallet_required_keys)
Пример #7
0
def request_handler(event, context):
    try:
        valid_event = validate_dict(
            data_dict=event,
            required_keys=REQUIRED_KEYS_FOR_CANCEL_ORDER_EVENT)
        if not valid_event:
            return generate_lambda_response(400,
                                            "Bad Request",
                                            cors_enabled=True)

        path_parameters = event.get("pathParameters", None)

        order_service = OrderService(obj_repo=repo)
        cancel_order_status = order_service.cancel_order_for_given_order_id(
            order_id=path_parameters["order_id"])
        response = generate_lambda_response(200, {
            "status": "success",
            "data": cancel_order_status
        },
                                            cors_enabled=True)
    except Exception as e:
        error_message = format_error_message(status="failed",
                                             error=repr(e),
                                             payload=payload_dict,
                                             net_id=NETWORK_ID,
                                             handler="cancel_order_handler")
        obj_util.report_slack(1, error_message, SLACK_HOOK)
        response = generate_lambda_response(500,
                                            error_message,
                                            cors_enabled=True)
        traceback.print_exc()
    return response
Пример #8
0
def get_channels(event, context):
    logger.info("Received request to get channel details from user address")
    try:
        query_string_parameters = event["queryStringParameters"]
        if validate_dict(query_string_parameters, ["wallet_address"]):
            wallet_address = query_string_parameters["wallet_address"]
            logger.info(
                f"Fetched values from request wallet_address: {wallet_address}"
            )
            response = obj_mpe.get_channels_by_user_address_v2(wallet_address)
            status_code = StatusCode.OK
        else:
            status_code = StatusCode.BAD_REQUEST
            response = "Bad Request"
            logger.error(response)
            logger.info(event)
    except Exception as e:
        logger.info(event)
        response = repr(e)
        utils.report_slack(str(response), SLACK_HOOK)
        logger.error(e)
        status_code = StatusCode.INTERNAL_SERVER_ERROR
    return generate_lambda_response(status_code=status_code,
                                    message=response,
                                    cors_enabled=True)
Пример #9
0
def request_handler(event, context):
    try:
        valid_event = validate_dict(data_dict=event, required_keys=REQUIRED_KEYS_FOR_LAMBDA_EVENT)
        if not valid_event:
            return generate_lambda_response(400, "Bad Request")

        path = event['path'].lower()
        method = event['httpMethod']

        method_found, payload_dict = extract_payload(method=method, event=event)
        if not method_found:
            return generate_lambda_response(405, "Method Not Allowed")

        path_exist, response_data = route_path(path=path, method=method, payload_dict=payload_dict)
        if not path_exist:
            return generate_lambda_response(404, "Not Found")

        if response_data is None:
            error_message = format_error_message(status="failed", error="Bad Request", resource=path,
                                                 payload=payload_dict, net_id=NETWORK_ID)
            obj_util.report_slack(1, error_message)
            response = generate_lambda_response(500, error_message)
        else:
            response = generate_lambda_response(200, {"status": "success", "data": response_data})
    except Exception as e:
        error_message = format_error_message(status="failed", error="Bad Request", resource=path,
                                             payload=payload_dict, net_id=NETWORK_ID)
        obj_util.report_slack(1, error_message)
        response = generate_lambda_response(500, error_message)
        traceback.print_exc()
    return response
def upload_file(event, context):
    headers = event["headers"]
    if "content-type" not in headers:
        if "Content-Type" not in headers:
            logger.error(f"Content type not found content type")
            raise InvalidContentType()
        else:
            content_type = headers["Content-Type"]
    else:
        content_type = headers["content-type"]

    username = event["requestContext"]["authorizer"]["claims"]["email"]
    query_string_parameter = event["queryStringParameters"]

    if content_type not in ALLOWED_CONTENT_TYPE:
        logger.error(f"Invalid Content type {content_type}")
        raise InvalidContentType()

    if not ("type" in query_string_parameter
            and query_string_parameter["type"] in UPLOAD_TYPE_DETAILS) or len(
                event["body"]) == 0:
        logger.error(
            f"Invalid request for content_type: {content_type} query_params: {query_string_parameter}"
        )
        raise BadRequestException()

    upload_request_type = query_string_parameter["type"]
    query_string_parameter.pop("type")
    if not validate_dict(
            query_string_parameter,
            UPLOAD_TYPE_DETAILS[upload_request_type]["required_query_params"]):
        logger.error(
            f"Failed to get required query params content_type: {content_type} "
            f"upload_type: {upload_request_type} params: {query_string_parameter}"
        )
        raise BadRequestException()

    file_extension = FILE_EXTENSION[content_type]
    temp_file_path = f"{TEMP_FILE_DIR}/{uuid4().hex}_upload.{file_extension}"
    raw_file_data = base64.b64decode(event["body"])

    with open(temp_file_path, 'wb') as file:
        file.write(raw_file_data)

    response = UploadService().store_file(upload_request_type, {
        "file_path": temp_file_path,
        "file_extension": file_extension
    }, query_string_parameter, username)

    return generate_lambda_response(StatusCode.OK, {
        "status": "success",
        "data": {
            "url": response
        },
        "error": {}
    },
                                    cors_enabled=True)
def get_document_types_handler(event, context):
    required_keys = ["countryCode"]
    if not validate_dict(event["pathParameters"], required_keys):
        raise BadRequestException()
    country_code = event["pathParameters"]["countryCode"]
    response = verification_service.get_document_types(country_code)
    return generate_lambda_response(StatusCode.OK, {
        "status": ResponseStatus.SUCCESS,
        "data": response
    })
def initiate(event, context):
    payload = json.loads(event["body"])
    username = event["requestContext"]["authorizer"]["claims"]["email"]
    required_keys = ["type"]
    if not validate_dict(payload, required_keys):
        raise BadRequestException()
    response = VerificationManager().initiate_verification(payload, username)
    return generate_lambda_response(StatusCode.CREATED,
                                    {"status": ResponseStatus.SUCCESS, "data": response, "error": {}},
                                    cors_enabled=True)
    def test_get_channel_details(self, mock_channels_from_contract,
                                 mock_channel_transactions):
        mock_channel_transactions.return_value = [{
            "address":
            "0x123",
            "is_default":
            1,
            "type":
            "GENERAL",
            "transactions": [{
                "org_id": "snet",
                "group_id": "default-group",
                "recipient": "0x123",
                "amount": 123,
                "transaction_type": "channelAddFunds",
                "currency": "USD",
                "status": "PENDING",
                "created_at": "2019-10-18 09:59:13"
            }]
        }]
        mock_channels_from_contract.return_value = [{
            "channel_id": 117,
            "recipient": "0x234",
            "balance_in_cogs": "135.00000000",
            "pending": "0E-8",
            "nonce": 0,
            "expiration": 11111111,
            "signer": "0x345",
            "status": "active"
        }]

        username = "******"
        org_id = "dummy"
        group_id = "dummy-group"

        channel_details = WalletService().get_channel_details(
            username, org_id, group_id)
        assert validate_dict(channel_details,
                             ["username", "org_id", "group_id", "wallets"])
        assert isinstance(channel_details["wallets"], list)
        assert validate_dict(channel_details["wallets"][0], ["channels"])
        assert isinstance(channel_details["wallets"][0]["channels"], list)
Пример #14
0
def create_organization(event, context):
    payload = json.loads(event["body"])
    required_keys = []
    username = event["requestContext"]["authorizer"]["claims"]["email"]
    if not validate_dict(payload, required_keys):
        raise BadRequestException()
    response = OrganizationPublisherService(None, username).create_organization(payload)
    return generate_lambda_response(
        StatusCode.OK,
        {"status": "success", "data": response, "error": {}}, cors_enabled=True
    )
def get_and_validate_upload_type(query_string_parameter):
    upload_request_type = "NOT_GIVEN"
    if "type" in query_string_parameter and query_string_parameter[
            "type"] in UPLOAD_TYPE_DETAILS:
        upload_request_type = query_string_parameter["type"]
        query_string_parameter.pop("type")
        if validate_dict(
                query_string_parameter,
                UPLOAD_TYPE_DETAILS[upload_request_type]
            ["required_query_params"]):
            return True, upload_request_type
    return False, upload_request_type
Пример #16
0
def get_service_details_using_org_id_service_id(event, context):
    logger.info(f"event: {event}")
    query_parameters = event["queryStringParameters"]
    if not validate_dict(query_parameters, ["org_id", "service_id"]):
        raise BadRequestException()
    org_id = query_parameters["org_id"]
    service_id = query_parameters["service_id"]
    response = ServicePublisherService.get_service_for_org_id_and_service_id(org_id, service_id)
    return generate_lambda_response(
        StatusCode.OK,
        {"status": "success", "data": response, "error": {}}, cors_enabled=True
    )
Пример #17
0
def execute(event, context):
    logger.info("Received request to execute order")
    try:
        username = event["requestContext"]["authorizer"]["claims"]["email"]
        payload = json.loads(event["body"])
        required_keys = ["order_id", "payment_id", "payment_details"]
        if validate_dict(payload, required_keys):
            response = OrderService(obj_repo=repo).execute_order(
                username, payload)
            status_code = StatusCode.CREATED
            status = ResponseStatus.SUCCESS
        else:
            status_code = StatusCode.BAD_REQUEST
            status = ResponseStatus.FAILED
            response = "Bad Request"
            logger.error(response)
            logger.info(event)
        error = {}
    except ChannelCreationFailed as e:
        response = e.get_wallet_details()
        logger.error(f"response: {response}\n"
                     f"event: {event}\n"
                     f"error: CHANNEL_CREATION_FAILED")
        error = Error.CHANNEL_CREATION_FAILED
        status = ResponseStatus.FAILED
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(1, str(error), SLACK_HOOK)

    except FundChannelFailed as e:
        response = "Failed to fund channel"
        logger.error(f"response: {response}\n"
                     f"event: {event}\n"
                     f"error: FUND_CHANNEL_FAILED")
        error = Error.FUND_CHANNEL_FAILED
        status = ResponseStatus.FAILED
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(1, str(error), SLACK_HOOK)

    except Exception as e:
        response = "Failed to execute order"
        logger.error(f"response: {response}\n"
                     f"event: {event}\n"
                     f"error: {repr(e)}")
        error = Error.UNDEFINED_ERROR
        status = ResponseStatus.FAILED
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(1, str(error), SLACK_HOOK)
        traceback.print_exc()
    return generate_lambda_response(status_code,
                                    make_response_body(status, response,
                                                       error),
                                    cors_enabled=True)
Пример #18
0
def record_create_channel_event(event, context):
    logger.info("Received request to initiate order")
    try:
        payload = json.loads(event["body"])
        required_keys = [
            "order_id", "sender", "signature", "r", "s", "v",
            "current_block_no", "group_id", "org_id", "amount", "currency",
            "recipient", "amount_in_cogs"
        ]
        if validate_dict(payload, required_keys):
            ChannelRepository().add_channel_transaction_history_record(
                ChannelTransactionHistory(
                    order_id=payload["order_id"],
                    amount=payload["amount"],
                    currency=payload["currency"],
                    type=payload.get("type", "openChannelByThirdParty"),
                    address=payload["sender"],
                    recipient=payload["recipient"],
                    signature=payload["signature"],
                    org_id=payload["org_id"],
                    group_id=payload["group_id"],
                    request_parameters=payload.get("request_parameters", ""),
                    transaction_hash=payload.get("transaction_hash", ""),
                    status=TransactionStatus.NOT_SUBMITTED))
            logger.info(f"Payload for create channel: {payload}")
            response = wallet_service.record_create_channel_event(payload)
            return generate_lambda_response(StatusCode.CREATED,
                                            make_response_body(
                                                ResponseStatus.SUCCESS,
                                                response, {}),
                                            cors_enabled=False)
        else:
            response = "Bad Request"
            logger.error(f"response: {response}\n" f"event: {event}")
            return generate_lambda_response(StatusCode.BAD_REQUEST,
                                            make_response_body(
                                                ResponseStatus.FAILED,
                                                response, {}),
                                            cors_enabled=False)
    except Exception as e:
        response = "Failed to record create channel event"
        logger.error(f"response: {response}\n"
                     f"stage: {NETWORK_ID}"
                     f"event: {event}\n"
                     f"error: {repr(e)}")
        utils.report_slack(str(repr(e)), SLACK_HOOK)
        traceback.print_exc()
        return generate_lambda_response(StatusCode.INTERNAL_SERVER_ERROR,
                                        make_response_body(
                                            ResponseStatus.FAILED, response,
                                            Error.undefined_error(repr(e))),
                                        cors_enabled=False)
Пример #19
0
def update_consumed_balance(event, context):
    logger.info("Received request to update consumed balance")
    try:
        path_parameters = event["pathParameters"]
        payload = json.loads(event["body"])
        if validate_dict(
                payload, ["OrganizationID", "ServiceID", "GroupID", "AuthorizedAmount",
                          "FullAmount", "ChannelId", "Nonce"]) \
                and "channel_id" in path_parameters:
            org_id = payload["OrganizationID"]
            service_id = payload["ServiceID"]
            group_id = payload["GroupID"]
            authorized_amount = payload["AuthorizedAmount"]
            full_amount = payload["FullAmount"]
            nonce = payload["Nonce"]
            channel_id = path_parameters["channel_id"]
            logger.info(
                f"Fetched values from request\n"
                f"org_id: {org_id} group_id: {group_id} service_id: {service_id} "
                f"authorized_amount: {authorized_amount} full_amount: {full_amount} nonce: {nonce}"
            )
            response = obj_mpe.update_consumed_balance(channel_id,
                                                       authorized_amount,
                                                       full_amount, nonce)
            return generate_lambda_response(StatusCode.CREATED,
                                            make_response_body(
                                                ResponseStatus.SUCCESS,
                                                response, {}),
                                            cors_enabled=True)
        else:
            logger.error("Bad Request")
            logger.info(event)
            return generate_lambda_response(StatusCode.BAD_REQUEST,
                                            make_response_body(
                                                ResponseStatus.FAILED,
                                                "Bad Request", {}),
                                            cors_enabled=True)

    except Exception as e:
        response = "Failed to update consumed balance"
        logger.error(response)
        logger.info(event)
        logger.error(e)
        error = Error.undefined_error(repr(e))
        utils.report_slack(str(error), SLACK_HOOK)
        traceback.print_exc()
        return generate_lambda_response(StatusCode.INTERNAL_SERVER_ERROR,
                                        make_response_body(
                                            ResponseStatus.FAILED, response,
                                            error),
                                        cors_enabled=True)
def create_channel(event, context):
    logger.info("Received request to initiate order")
    try:
        payload = json.loads(event["body"])
        required_keys = [
            "order_id", "sender", "signature", "r", "s", "v",
            "current_block_no", "group_id", "org_id", "amount", "currency",
            "recipient", "amount_in_cogs"
        ]
        if validate_dict(payload, required_keys):
            logger.info(f"Payload for create channel: {payload}")
            response = wallet_service.open_channel_by_third_party(
                order_id=payload['order_id'],
                sender=payload['sender'],
                signature=payload['signature'],
                r=payload['r'],
                s=payload['s'],
                v=payload['v'],
                current_block_no=payload['current_block_no'],
                group_id=payload['group_id'],
                org_id=payload["org_id"],
                recipient=payload['recipient'],
                amount=payload['amount'],
                currency=payload['currency'],
                amount_in_cogs=payload['amount_in_cogs'])
            return generate_lambda_response(StatusCode.CREATED,
                                            make_response_body(
                                                ResponseStatus.SUCCESS,
                                                response, {}),
                                            cors_enabled=False)
        else:
            response = "Bad Request"
            logger.error(f"response: {response}\n" f"event: {event}")
            return generate_lambda_response(StatusCode.BAD_REQUEST,
                                            make_response_body(
                                                ResponseStatus.FAILED,
                                                response, {}),
                                            cors_enabled=False)
    except Exception as e:
        response = "Failed create channel"
        logger.error(f"response: {response}\n"
                     f"event: {event}\n"
                     f"error: {repr(e)}")
        utils.report_slack(1, str(repr(e)), SLACK_HOOK)
        traceback.print_exc()
        return generate_lambda_response(StatusCode.INTERNAL_SERVER_ERROR,
                                        make_response_body(
                                            ResponseStatus.FAILED, response,
                                            Error.undefined_error(repr(e))),
                                        cors_enabled=False)
def register_org_member(event, context):
    username = event["requestContext"]["authorizer"]["claims"]["email"]
    payload = json.loads(event["body"])
    required_keys = ["wallet_address", "invite_code"]
    if not validate_dict(payload, required_keys):
        raise BadRequestException()
    response = OrganizationOrchestratorService().register_org_member(
        username, payload)
    return generate_lambda_response(StatusCode.CREATED, {
        "status": ResponseStatus.SUCCESS,
        "data": response,
        "error": {}
    },
                                    cors_enabled=True)
def request_handler(event, context):
    logger.info(f"Wallets::event: {event}")
    try:
        valid_event = validate_dict(
            data_dict=event, required_keys=REQUIRED_KEYS_FOR_LAMBDA_EVENT)
        if not valid_event:
            return generate_lambda_response(400, StatusDescription.BAD_REQUEST)

        path = event['path'].lower()
        method = event['httpMethod']
        method_found, path_parameters, payload_dict = extract_payload(
            method=method, event=event)
        if not method_found:
            return generate_lambda_response(
                405, ErrorDescription.METHOD_NOT_ALLOWED)

        path_exist, response_data = route_path(path=path,
                                               method=method,
                                               payload_dict=payload_dict,
                                               path_parameters=path_parameters)

        if not path_exist:
            return generate_lambda_response(404, ErrorDescription.NOT_FOUND)

        if response_data is None:
            error_message = format_error_message(
                status="failed",
                error=StatusDescription.BAD_REQUEST,
                resource=path,
                payload=payload_dict,
                net_id=NETWORK_ID)
            util.report_slack(error_message, SLACK_HOOK)
            response = generate_lambda_response(500, error_message)
        else:
            response = generate_lambda_response(200, {
                "status": "success",
                "data": response_data
            })
    except Exception as e:
        error_message = format_error_message(
            status="failed",
            error=StatusDescription.BAD_REQUEST,
            resource=path,
            payload=payload_dict,
            net_id=NETWORK_ID)
        util.report_slack(error_message, SLACK_HOOK)
        response = generate_lambda_response(500, error_message)
        traceback.print_exc()
    return response
Пример #23
0
def publish_members(event, context):
    username = event["requestContext"]["authorizer"]["claims"]["email"]
    payload = json.loads(event["body"])
    path_parameters = event["pathParameters"]

    if "org_uuid" not in path_parameters or not validate_dict(payload, ["transaction_hash", "members"]):
        raise BadRequestException()
    org_uuid = path_parameters["org_uuid"]
    transaction_hash = payload["transaction_hash"]
    org_members = payload["members"]
    response = OrganizationPublisherService(org_uuid, username).publish_members(transaction_hash, org_members)
    return generate_lambda_response(
        StatusCode.CREATED,
        {"status": "success", "data": response, "error": {}}, cors_enabled=True
    )
Пример #24
0
def update_org(event, context):
    payload = json.loads(event["body"])
    path_parameters = event["pathParameters"]
    required_keys = []
    action = event["queryStringParameters"].get("action", None)
    username = event["requestContext"]["authorizer"]["claims"]["email"]
    org_uuid = path_parameters["org_uuid"]
    if not validate_dict(payload, required_keys):
        raise BadRequestException()
    org_service = OrganizationPublisherService(org_uuid, username)
    if action in [OrganizationActions.DRAFT.value, OrganizationActions.SUBMIT.value]:
        response = org_service.update_organization(payload, action)
    else:
        raise Exception("Invalid action")
    return generate_lambda_response(
        StatusCode.OK,
        {"status": "success", "data": response, "error": {}}, cors_enabled=True
    )
Пример #25
0
def initiate(event, context):
    logger.info("Received request to initiate order")
    try:
        username = event["requestContext"]["authorizer"]["claims"]["email"]
        payload = json.loads(event["body"])
        required_keys = ["price", "item_details", "payment_method"]
        if validate_dict(payload, required_keys):
            response = OrderService(obj_repo=repo).initiate_order(
                username, payload)
            status_code = StatusCode.CREATED
            status = ResponseStatus.SUCCESS
        else:
            status_code = StatusCode.BAD_REQUEST
            status = ResponseStatus.FAILED
            error = {}
            response = "Bad Request"
            logger.error(f"response: {response}\n" f"event: {event}")
        error = {}

    except PaymentInitiateFailed:
        response = "Failed to initiate order"
        error = Error.PAYMENT_INITIATE_FAILED
        logger.error(f"response: {response}\n"
                     f"event: {event}\n"
                     f"error: PAYMENT_INITIATE_FAILED")
        status = ResponseStatus.FAILED
        utils.report_slack(1, error, SLACK_HOOK)
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        traceback.print_exc()

    except Exception as e:
        response = "Failed to initiate order"
        logger.error(f"response: {response}\n"
                     f"event: {event}\n"
                     f"error: {repr(e)}")
        traceback.print_exc()
        error = Error.UNDEFINED_ERROR
        status = ResponseStatus.FAILED
        status_code = StatusCode.INTERNAL_SERVER_ERROR
        utils.report_slack(1, str(error), SLACK_HOOK)
    return generate_lambda_response(status_code,
                                    make_response_body(status, response,
                                                       error),
                                    cors_enabled=True)
def get_agi_fiat_rate(event, context):
    logger.info("Received request for AGIX-USD rate {event}")
    try:
        valid_event = validate_dict(
            data_dict=event,
            required_keys=REQUIRED_KEYS_FOR_CURRENCY_TO_TOKEN_CONVERSION)
        if (valid_event):

            path_parameters = event["pathParameters"]
            query_string_parameters = event["queryStringParameters"]

            currency = path_parameters["currency"]
            amount = query_string_parameters["amount"]
            rate = get_cogs_amount(crypto='AGIX',
                                   fiat=currency,
                                   fiat_rate=amount)

            if rate is not None:
                conversion_data = {
                    "base": currency,
                    "amount": amount,
                    "amount_in_agi": str(rate)
                }
                response = generate_lambda_response(200, {
                    "status": "success",
                    "data": conversion_data
                },
                                                    cors_enabled=True)
            else:
                response = generate_lambda_response(400,
                                                    "Failed to convert",
                                                    cors_enabled=True)
        else:
            response = generate_lambda_response(400,
                                                "Bad Request",
                                                cors_enabled=True)
    except Exception as e:
        logger.info("Failed to response to AGIX-USD rate {e}")
        response = generate_lambda_response(400,
                                            "Bad Request",
                                            cors_enabled=True)
    return response
Пример #27
0
 def test_manage_create_order(self, mock_lambda_invoke):
     mock_lambda_invoke.return_value = {
         'statusCode':
         201,
         'body':
         json.dumps({
             "order_id": "e33404a2-f574-11e9-9a93-3abe2d8567d5",
             "item_details": {
                 "item": "AGI",
                 "quantity": 1,
                 "org_id": "snet",
                 "group_id": "GROUP-123",
                 "service_id": "freecall",
                 "recipient": "0x123",
                 "order_type": "CREATE_WALLET_AND_CHANNEL",
                 "wallet_address": "",
                 "channel_id": ""
             },
             "price": {
                 "amount": 1,
                 "currency": "USD"
             }
         })
     }
     username = "******"
     item_details = {
         "item": "AGI",
         "quantity": 1,
         "org_id": "snet",
         "group_id": "GROUP-123",
         "service_id": "freecall",
         "recipient": "0x123",
         "order_type": "CREATE_WALLET_AND_CHANNEL",
         "wallet_address": "",
         "channel_id": ""
     }
     price = {"amount": 1, "currency": "USD"}
     order_details = self.order_service.manage_create_order(
         username, item_details, price)
     assert validate_dict(order_details,
                          ["order_id", "item_details", "price"])
 def test_get_channels_from_contract(self, invoke_lambda_mock):
     invoke_lambda_mock.return_value = {
         "statusCode":
         200,
         "body":
         json.dumps({
             "status": "success",
             "data": {
                 "username":
                 "******",
                 "group_id":
                 "dummy-group",
                 "org_id":
                 "dummy",
                 "channels": [{
                     "channel_id": 117,
                     "recipient": "0x234",
                     "balance_in_cogs": "135.00000000",
                     "pending": "0E-8",
                     "nonce": 0,
                     "expiration": 11111111,
                     "signer": "0x345",
                     "status": "active"
                 }]
             }
         })
     }
     username = "******"
     org_id = "dummy"
     group_id = "dummy-group"
     transaction_keys = [
         "channel_id", "recipient", "balance_in_cogs", "pending", "nonce",
         "expiration", "signer", "status"
     ]
     channel_transactions = WalletService().get_channels_from_contract(
         username, org_id, group_id)
     assert isinstance(channel_transactions, list)
     if len(channel_transactions) > 0:
         transaction = channel_transactions[0]
         assert validate_dict(transaction, transaction_keys)
def record_create_channel_event(event, context):
    logger.info("Received request to initiate order")
    try:
        payload = json.loads(event["body"])
        required_keys = [
            "order_id", "sender", "signature", "r", "s", "v",
            "current_block_no", "group_id", "org_id", "amount", "currency",
            "recipient", "amount_in_cogs"
        ]
        if validate_dict(payload, required_keys):
            logger.info(f"Payload for create channel: {payload}")
            response = wallet_service.record_create_channel_event(payload)
            return generate_lambda_response(StatusCode.CREATED,
                                            make_response_body(
                                                ResponseStatus.SUCCESS,
                                                response, {}),
                                            cors_enabled=False)
        else:
            response = "Bad Request"
            logger.error(f"response: {response}\n" f"event: {event}")
            return generate_lambda_response(StatusCode.BAD_REQUEST,
                                            make_response_body(
                                                ResponseStatus.FAILED,
                                                response, {}),
                                            cors_enabled=False)
    except Exception as e:
        response = "Failed to record create channel event"
        logger.error(f"response: {response}\n"
                     f"stage: {NETWORK_ID}"
                     f"event: {event}\n"
                     f"error: {repr(e)}")
        utils.report_slack(1, str(repr(e)), SLACK_HOOK)
        traceback.print_exc()
        return generate_lambda_response(StatusCode.INTERNAL_SERVER_ERROR,
                                        make_response_body(
                                            ResponseStatus.FAILED, response,
                                            Error.undefined_error(repr(e))),
                                        cors_enabled=False)
Пример #30
0
def currency_to_token_conversion(event, context):
    try:
        logger.info(f"currency_to_token_conversion::event: {event}")
        valid_event = validate_dict(
            data_dict=event,
            required_keys=REQUIRED_KEYS_FOR_CURRENCY_TO_TOKEN_CONVERSION)
        if not valid_event:
            return generate_lambda_response(400,
                                            "Bad Request",
                                            cors_enabled=True)

        path_parameters = event["pathParameters"]
        query_string_parameters = event["queryStringParameters"]

        order_service = OrderService(obj_repo=repo)
        response_data = order_service.currency_to_token(
            currency=path_parameters["currency"],
            amount=query_string_parameters["amount"])
        response = generate_lambda_response(200, {
            "status": "success",
            "data": response_data
        },
                                            cors_enabled=True)
        logger.info(f"currency_to_token_conversion::response: {response}")
    except Exception as e:
        error_message = format_error_message(
            status=ResponseStatus.FAILED,
            error=repr(e),
            payload=path_parameters,
            net_id=NETWORK_ID,
            handler="currency-to-token-conversion")
        utils.report_slack(1, error_message, SLACK_HOOK)
        response = generate_lambda_response(500,
                                            error_message,
                                            cors_enabled=True)
        traceback.print_exc()
    return response