Пример #1
0
def put_policy_using_put(request, response_dict, config):
    json_data = request.get_json()
    creds = ResponseHelper.get_credentials(json_data, config)

    current_app.logger.info("creds: {}".format(creds))

    required = {'id', 'jsonBody', 'ric', 'service'}
    param_keys = {'id', 'ric', 'service'}
    optional = {"type"}
    data_keys = param_keys.copy()
    keys = set(json_data.keys())
    if not required <= keys:
        raise BadRequestException(
            406, "Request is missing required values {}".format(required))
    if optional <= keys: data_keys.update(optional)
    param = {}
    body = {}
    for key in data_keys:
        param[key] = json_data[key]
    body['jsonBody'] = json_data['jsonBody']

    url = ResponseHelper.create_url(config=config, uri_path="/policy")
    res = requests.put(url, auth=creds, params=param, json=body)
    response = {"status_code": res.status_code, "result": res.json()}
    response_dict['vthResponse']['resultData'] = response
    return response_dict
Пример #2
0
def route_check2(get_function=None,
                 post_function=None,
                 put_function=None,
                 delete_function=None):
    """
     Info:
        Since all routes do the same pre-check and have a similar skeleton, this function just refactored the pre-check for code reuse
     Arguments (**kwargs): pass in the specified key(s) and  method(s) that handle the type of method, method must be allowed by route decorator
        get_function => type: function
        put_function => type: function
        delete_function => type: function
    Returns:
        returns the return of the function call, typically a jsonified response.
        you can capture response in a var and execute logic or you can just return the function call/response 
    E.G.:
        response = route_check(post_function = handle_post)
        return route_check(get_function = handle_get, post_function = handle_post)
    """
    response_dict = ResponseHelper.vth_response_dic()
    start_time = unix_time_millis(datetime.datetime.now())
    status_code = 200
    if request.is_json and ResponseHelper.valid_json(request.data):
        if (request.method == 'GET'):
            response_dict = get_function(request, response_dict, config)
        elif (request.method == 'POST'):
            response_dict = post_function(request, response_dict, config)
        elif (request.method == 'PUT'):
            response_dict = put_function(request, response_dict, config)
        elif (request.method == 'DELETE'):
            response_dict = delete_function(request, response_dict, config)
    else:
        raise BadRequestException(406, "Invalid Json")
    end_time = unix_time_millis(datetime.datetime.now())
    response_dict['vthResponse']['testDurationMS'] = end_time - start_time
    return jsonify(response_dict), status_code
Пример #3
0
def valid_string_json(
    string,
    response_message="Invalid json string in query or jsonBody, format requires quoted json object e.g. \"{'key':'value, key2:{'innerKey':'innerValue'}}\""
):
    try:
        string_to_dict = ast.literal_eval(string)
    except (Exception):
        raise BadRequestException(406, response_message)
    return True
Пример #4
0
def get_policy_using_get(request, response_dict, config):
    json_data = request.get_json()
    if 'id' not in json_data:
        raise BadRequestException(406, "Request is missing id")
    param = {'id': json_data['id']}
    creds = ResponseHelper.get_credentials(json_data, config)
    url = ResponseHelper.create_url(config=config, uri_path="/policy")
    res = requests.get(url, auth=creds, params=param)
    response = {"status_code": res.status_code, "result": res.json()}
    response_dict['vthResponse']['resultData'] = response

    return response_dict
Пример #5
0
def route_check(config=None, get_function=None, post_function=None, put_function=None, delete_function=None):
    """
     Info:
        Since all routes do the same pre-check and have a similar skeleton, this function just refactored the pre-check for code reuse
     Arguments (**kwargs): pass in the specified key(s) and  method(s) that handle the type of method, method must be allowed by route decorator
        get_function => type: function
        put_function => type: function
        delete_function => type: function
    Returns:
        returns the return of the function call, typically a jsonified response.
        you can capture response in a var and execute logic or you can just return the function call/response 
    E.G.:
        response = route_check(post_function = handle_post)
        return route_check(get_function = handle_get, post_function = handle_post)
    """
    if not request.is_json: raise BadRequestException(406, "Invalid Json Request")

    response_dict = vth_response_dic()
    start_time = unix_time_millis(datetime.datetime.now())
    status_code = 200
    ret_url = request.args.get('retURL')

    query = ""
    json_body = ""
    request_data = request.json
    json_keys = set(request_data)
    action_request = request_data.get("action").lower()
    valid_actions = {"geta1policytype", "geta1policy", "puta1policy", "deletea1policy", "geta1policystatus"}
    required_keys = {"action", "auth", "action_data"}

    #check for valid action and json request contains required keys
    if not required_keys <= json_keys: raise BadRequestException(406, "Json request is missing required keys {}".format(required_keys))
    if not action_request in valid_actions: raise BadRequestException(406, "Action is not supported {}".format(action_request))
    #check request's action_data key contains required keys
    if 'query' not in request.json['action_data']: raise BadRequestException(406, "action_data must contain query and jsonBody ")
    if 'jsonBody' not in request.json['action_data']: raise BadRequestException(406, "action_data must contain query and jsonBody")

    query = request.json['action_data']['query'] if 'query' in request.json['action_data'] else ""
    json_body = request.json['action_data']['jsonBody'] if 'jsonBody' in request.json['action_data'] else ""

    if valid_string_json(query) and valid_string_json(json_body):
        if(request.method == 'GET'):
            response_dict = get_function(request, response_dict, config)
        elif(request.method == 'POST'):
            response_dict = post_function(request, response_dict, config)
        elif(request.method == 'PUT'):
            response_dict = put_function(request, response_dict, config)
        elif(request.method == 'DELETE'):
            response_dict = delete_function(request, response_dict, config)
    else:
        raise BadRequestException(406, "Invalid JSON Strings")
    end_time = unix_time_millis(datetime.datetime.now())
    response_dict['vthResponse']['testDurationMS'] = end_time-start_time
    if ret_url is not None:
        sendCallback(ret_url,response_dict)
        return '',200
    return jsonify(response_dict), status_code
Пример #6
0
def execute_action(request, response_dict, config):
    headers = ResponseHelper.create_headers();
    request_data = request.json
    action_request = request_data.get("action").lower()
    method = request_data.get("method").upper()
    creds = ResponseHelper.get_credentials(request_data, config)

    proxies = ResponseHelper.get_proxies(config)
    action = "services/keepalive" if action_request == "keepalive" else action_request
    url = ResponseHelper.create_url(config=config, uri_path="/"+action)
#    ret_url = request.args.get('retURL')


    json_req = ast.literal_eval(request_data["action_data"]["jsonBody"])
    query_params = ast.literal_eval(request_data["action_data"]["query"])
    current_app.logger.info("Requesting Url: {}, params: {}, body: {}, auth: {}, proxies: {}".format(url, query_params, json_req, creds, proxies))
    try:
        if(method == "GET"):
            res = requests.get(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)
        elif(method == "POST"):
            res = requests.post(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)
        elif(method == "PUT"):
            res = requests.put(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)
        elif(method == "DELETE"):
            res = requests.delete(url, proxies=proxies, auth=creds, headers=headers, params=query_params, json=json_req)
        else: 
            raise BadRequestException(406, "Method Not Supported")
        response = {
                "status_code":res.status_code,
                "result": res.json()
                }
    except(json.decoder.JSONDecodeError):
        response = {
                "status_code":res.status_code,
                "result": res.reason
                }
    except requests.exceptions.RequestException:
        response = {
                "status_code":504,
                "result": "Something Happned"
                }
    finally:
        response_dict['vthResponse']['resultData'] = response
 #       if ret_url is not None:
 #           ResponseHelper.sendCallback(ret_url,response_dict)
 #           return '',200
        return response_dict
Пример #7
0
def delete_policy_using_delete(request, response_dict, config):
    json_data = request.get_json()
    creds = ResponseHelper.get_credentials(json_data, config)

    current_app.logger.info("creds: {}".format(creds))

    keys = set(json_data.keys())
    required = {'id'}
    if not required <= keys:
        raise BadRequestException(
            406, "Request is missing required values {}".format(required))
    param = {'id': json_data['id']}

    url = ResponseHelper.create_url(config=config, uri_path="/policy")
    res = requests.delete(url, auth=creds, params=param)
    response = {"status_code": res.status_code, "result": res.json()}
    response_dict['vthResponse']['resultData'] = response
    return response_dict
Пример #8
0
def get_policy_status_using_get(request, response_dict, config):
    json_data = request.get_json()
    #username = config['auth']['username'] if 'username' not in json_data else json_data['username']
    #password = config['auth']['password'] if 'password' not in json_data else json_data['password']
    #creds = (username, password)
    creds = ResponseHelper.get_credentials(json_data, config)
    current_app.logger.info("creds: {}".format(creds))

    keys = set(json_data.keys())
    required = {'id'}
    if not required <= keys:
        raise BadRequestException(
            406, "Request is missing required values {}".format(required))
    param = {"id": json_data["id"]}

    response_dict['vthResponse']['resultData'] = param
    #api_response = requests.get(url, credentials=creds, params=param)
    return response_dict
Пример #9
0
def get_policy_schema_using_get(request, response_dict, config):
    json_data = request.get_json()
    #username = config['auth']['username'] if 'username' not in json_data else json_data['username']
    #password = config['auth']['password'] if 'password' not in json_data else json_data['password']
    #creds = (username, password)
    creds = ResponseHelper.get_credentials(json_data, config)
    current_app.logger.info("creds: {}".format(creds))

    keys = set(json_data.keys())
    required = {'id'}
    if not required <= keys:
        raise BadRequestException(
            406, "Request is missing required values {}".format(required))
    param = {'id': json_data['id']}

    url = ResponseHelper.create_url(config=config, uri_path="/policy_schema")
    res = requests.get(url, auth=creds, params=param)
    response = {"status_code": res.status_code, "result": res.json()}
    response_dict['vthResponse']['resultData'] = response
    return response_dict