Esempio n. 1
0
def handler(event, _):
    """
    Lambda function handler for /backend/pricing
    """

    # Verify that this is a request with IAM credentials
    if iam_user_id(event) is None:
        logger.warning({"message": "User ARN not found in event"})
        return response("Unauthorized", 403)

    # Extract the request body
    try:
        body = json.loads(event["body"])
    except Exception as exc:  # pylint: disable=broad-except
        logger.warning("Exception caught: %s", exc)
        return response("Failed to parse JSON body", 400)

    for key in ["products", "address"]:
        if key not in body:
            logger.info({
                "message": "Missing '{}' in body".format(key),
                "body": body
            })
            return response("Missing '{}' in body".format(key), 400)

    # Calculate the delivery pricing
    pricing = get_pricing(body["products"], body["address"])
    logger.debug({
        "message": "Estimated delivery pricing to {}".format(pricing),
        "pricing": pricing
    })

    # Send the response back
    return response({"pricing": pricing})
Esempio n. 2
0
def handler(event, _):
    """
    Lambda function handler for /backend/validate
    """

    user_id = iam_user_id(event)
    if user_id is None:
        logger.warning({"message": "User ARN not found in event"})
        return response("Unauthorized", 401)

    # Extract the list of products
    try:
        body = json.loads(event["body"])
    except Exception as exc: # pylint: disable=broad-except
        logger.warning("Exception caught: %s", exc)
        return response("Failed to parse JSON body", 400)

    if "products" not in body:
        return response("Missing 'products' in body", 400)

    products, reason = validate_products(body["products"])

    if len(products) > 0:
        return response({
            "message": reason,
            "products": products
        }, 200)

    return response("All products are valid")
Esempio n. 3
0
def handler(event, _):
    """
    Lambda function handler
    """

    user_id = iam_user_id(event)
    if user_id is None:
        logger.warning({"message": "User ARN not found in event"})
        return response("Unauthorized", 401)

    # Extract the body
    try:
        body = json.loads(event["body"])
    except Exception as exc: # pylint: disable=broad-except
        logger.warning("Exception caught: %s", exc)
        return response("Failed to parse JSON body", 400)

    for key in ["paymentToken", "total"]:
        if key not in body:
            logger.warning({
                "message": "Missing '{}' in request body.".format(key),
                "body": body
            })
            return response("Missing '{}' in request body.".format(key), 400)

    valid = validate_payment_token(body["paymentToken"], body["total"])

    return response({
        "ok": valid
    })
def handler(event, _):
    """
    Lambda handler
    """

    try:
        connection_id = event["requestContext"]["connectionId"]
    except (KeyError, TypeError):
        logger.error({
            "message": "Missing connection ID in event",
            "event": event
        })
        return response("Missing connection ID", 400)

    logger.debug({
        "message": f"Connection {connection_id} closing",
        "event": event
    })

    # disable_rule must happen after delete_id, as it checks if there are
    # active connections before deleting the rule.
    delete_id(connection_id)
    disable_rule()

    return response("Disconnected")
def test_response_status():
    """
    Test response() with a different status code
    """

    status_code = 400
    retval = apigateway.response("Message", status_code)
    assert retval["statusCode"] == status_code
def test_response_dict():
    """
    Test response() with a dict as input
    """

    obj = {"key": "value"}
    retval = apigateway.response(obj)

    assert retval["body"] == json.dumps(obj)
    assert retval["statusCode"] == 200
def test_response_string():
    """
    Test response() with a string as input
    """

    msg = "This is a test"
    retval = apigateway.response(msg)

    assert retval["body"] == json.dumps({"message": msg})
    assert retval["statusCode"] == 200
def handler(event, _):
    """
    Lambda function handler for GetOrder
    """

    logger.debug({"message": "Event received", "event": event})

    # Retrieve the userId
    user_id = iam_user_id(event)
    if user_id is not None:
        logger.info({
            "message": "Received get order from IAM user",
            "userArn": user_id
        })
        tracer.put_annotation("userArn", user_id)
        tracer.put_annotation("iamUser", True)
        iam_user = True
    else:
        logger.warning({"message": "User ID not found in event"})
        return response("Unauthorized", 401)

    # Retrieve the orderId
    try:
        order_id = event["pathParameters"]["orderId"]
    except (KeyError, TypeError):
        logger.warning({"message": "Order ID not found in event"})
        return response("Missing orderId", 400)

    # Set a trace annotation
    tracer.put_annotation("orderId", order_id)

    # Retrieve the order from DynamoDB
    order = get_order(order_id)

    # Check that the order can be sent to the user
    # This includes both when the item is not found and when the user IDs do
    # not match.
    if order is None or (not iam_user and user_id != order["userId"]):
        return response("Order not found", 404)

    # Send the response
    return response(order)
def handler(event, _):
    """
    Lambda handler
    """

    try:
        connection_id = event["requestContext"]["connectionId"]
    except (KeyError, TypeError):
        logger.error({
            "message": "Missing connection ID in event",
            "event": event
        })
        return response("Missing connection ID", 400)

    try:
        body = json.loads(event["body"])
    except json.decoder.JSONDecodeError:
        logger.error({
            "message": "Failed to parse request body",
            "event": event
        })
        return response("Failed to parse request body", 400)

    try:
        body = json.loads(event["body"])
        service_name = body["serviceName"]
    except (KeyError, TypeError):
        logger.warning({
            "message": "Missing 'serviceName' in request body",
            "event": event
        })
        return response("Missing 'serviceName' in request body", 400)

    logger.debug({
        "message": f"Register {connection_id} with service '{service_name}'",
        "event": event
    })

    register_service(connection_id, service_name)

    return response("Connected")
def handler(event, _):
    """
    Lambda handler
    """

    try:
        connection_id = event["requestContext"]["connectionId"]
    except (KeyError, TypeError):
        logger.error({
            "message": "Missing connection ID in event",
            "event": event
        })
        return response("Missing connection ID", 400)

    logger.debug({
        "message": f"New connection {connection_id}",
        "event": event
    })

    store_id(connection_id)

    return response("Connected")