コード例 #1
0
    def validate_set_local_table_name_request(self, request: flask.request):
        is_all_first_lvl_fields_defined = (
            self.is_admin_header_valid(request.headers)
            and TABLE_NAME_FIELD_NAME in request.get_json()
            and NEW_LOCAL_TABLE_NAME_FILED_NAME in request.get_json()
        )

        if not is_all_first_lvl_fields_defined:
            return False

        is_path_to_old_table_correct = self.is_defined_local_table_name_or_full_path(
            request.get_json()[TABLE_NAME_FIELD_NAME]
        )

        return is_path_to_old_table_correct and is_all_first_lvl_fields_defined
コード例 #2
0
def findParamsFromRequest(r: request):
    params = {}
    try:
        if r.args:
            params.update(r.args)
        if r.form:
            params.update(r.form)
        try:
            if j := r.get_json():
                params.update(j)
        except:
            pass
    except:
        pass
    return params
コード例 #3
0
def json_payload(request: flask.request) -> dict:
    """
    Verify that a flask.request object has a JSON payload and
    that it does not contain syntax errors.

    Args:
        request (flask.request): A request object that you want to
            verify has a valid JSON payload.

    Raises:
        ValueError: If the incoming request object is either missing
    """

    try:
        request_payload = request.get_json()
    except BadRequest:
        raise ValueError(
            "JSON payload contains syntax errors. Please fix and try again.")
    else:
        if request_payload is None:
            raise ValueError(
                "No JSON payload present. Make sure that "
                "the appropriate 'content-type' header is included "
                "in your request.")

        required_elements = {
            "id", "firstName", "lastName", "telephone", "email", "notes"
        }

        if not required_elements.issubset(request_payload.keys()):
            response = "Missing required payload elements. The following elements are required: {}".format(
                required_elements.difference(request_payload.keys()))
            raise ValueError(response)
コード例 #4
0
def _is_valid_slack_request(req: request) -> None:
    """
    This function ensures that the request we received came from Slack.
    Details on the algorithm here can be found at:
    https://api.slack.com/docs/verifying-requests-from-slack

    :param req: Flask request object
    :return: bool indicating whether or not the request is valid.
    """
    req_timestamp = req.headers.get("X-Slack-Request-Timestamp")
    if abs(int(datetime.now().timestamp()) - int(req_timestamp)) > 60 * 5:
        logger.error("This request is quite old. Could be a replay attack. Bailing.")
        abort(403)

    req_signature = req.headers.get("X-Slack-Signature")
    req_data = req.get_data().decode("utf-8")
    logger.debug("Request data:" + req_data)
    basestring = f"{VERSION_NUMBER}:{req_timestamp}:{req_data}".encode("utf-8")
    expected_signature = (
        "v0="
        + hmac.new(
            slack_cfg.get("signing_secret").encode("utf-8"), basestring, hashlib.sha256,
        ).hexdigest()
    )
    if not hmac.compare_digest(expected_signature, req_signature):
        logging.error("Request is improperly signed.")
        abort(403)
コード例 #5
0
def save_text(req: request) -> Tuple[Union[None, str], Union[None, str]]:
    """
    Extract json text or file from request and save it on disk.
    """

    json_data = req.get_json()
    if json_data:
        if not isinstance(json_data, dict) or "text" not in json_data:
            return (None, "Incorrect text payload")
        text = json_data["text"]
        filename = f"{str(uuid.uuid4())}.txt"
        filepath = os.path.join(UPLOAD_FOLDER, filename)
        with open(filepath, "w") as w:
            w.write(text)
            return (filename, None)

    file = req.files["file"]
    if not utils.is_allowed_file(file.filename):
        return (None, "Incorrect extension")

    ext = file.filename.rsplit(".", 1)[1]
    filename = f"{str(uuid.uuid4())}.{ext}"
    file.save(os.path.join(UPLOAD_FOLDER, filename))

    return (filename, None)
コード例 #6
0
def json_payload(request: flask.request) -> dict:
    """
    Verify that a flask.request object has a JSON payload and
    that it does not contain syntax errors.

    Args:
        request (flask.request): A request object that you want to
            verify has a valid JSON payload.

    Raises:
        ValueError: If the incoming request object is either missing
    """

    try:
        request_payload = request.get_json()
    except BadRequest:
        raise ValueError(
            "JSON payload contains syntax errors. Please fix and try again.")
    else:
        if request_payload is None:
            raise ValueError(
                "No JSON payload present. Make sure that "
                "the appropriate 'content-type' header is included "
                "in your request.")

        required_elements = {"id", "firstName", "lastName", "telephone",
                             "email", "notes"}

        if not required_elements.issubset(request_payload.keys()):
            response = "Missing required payload elements. The following elements are required: {}".format(
                            required_elements.difference(request_payload.keys()))
            raise ValueError(response)
コード例 #7
0
    def __call__(self, _request: flask.request, *args, **kwargs) -> dict:
        """

        """
        incoming_json = _request.get_json()
        return {
            "engine_incoming_json": incoming_json,
            "response_text": "Generic Response With New Setup"
        }
コード例 #8
0
def extract_slack_info(r: request):
    try:
        data = r.get_data(as_text=True)
        timestamp = r.headers.get("X-Slack-Request-Timestamp")
        signature = r.headers.get("X-Slack-Signature")
        return SlackVerification(data, timestamp, signature)
    except Exception as e:
        # If it makes it here, the request probably isn't from Slack.
        logging.error(e)
        return None
コード例 #9
0
ファイル: app.py プロジェクト: ursi-2020/technical-base
def add_request(req: request, name: str, description: str):
    request_list.append({
        "url": req.base_url,
        "args": req.args,
        "headers": req.headers.to_wsgi_list(),
        "body": req.get_data(as_text=True),
        "name": name,
        "description": description,
        "real_time": datetime.now().strftime(sch.time_format),
        "fake_time": sch.fake_clock.get_time().strftime(sch.time_format)
    })
コード例 #10
0
def __validate_flask_payload(req_val: flask.request):
    """
        Sub method of helper.validate_post_req. Just checking if request holds a json payload
        :param  req_val:     payload to be validated
        :return:             [False, message text] in case it fails. [json_payload] in case it is OK
        """
    if not req_val.data or not req_val.get_json(silent=True):
        return MethodResponse(message="NO Json in payload")
    req_content = req_val.json
    if not req_content or type(req_content) != dict:
        return MethodResponse(message='Paylaod not formatted properly')
    return MethodResponse(success=True, data=req_content)
コード例 #11
0
def guitar_to_dulcimer_tab(request: flask.request):
    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        return '', 204, options_headers

    request_json = request.get_json()
    if request_json and 'tab' in request_json:
        tab_string = request_json['tab']
        semitone_transpose = int(request_json['semitoneTranspose'])
    else:
        return 'No guitar tab passed in', 200, main_headers

    dulcimer_tab = guitar_tab_lines_to_dulcimer(
        tab_lines=parse_tab_string(tab_string),
        semitone_transpose=semitone_transpose)

    return dulcimer_tab, 200, main_headers
コード例 #12
0
def update(req: request, task_name: str):
    """
    Updates an existing task.

    It may return 404 if task was not found.
    It may return 400 if payload does not contain the necessary fields (name, description and status).
    It may return 400 if payload contains the name of a task that is already registered.
    It may return 400 if payload contains status with invalid value.
    If everything goes well, it returns 200.
    """
    logger.info(f'HTTP Request to update a task with data: {req}')
    request_payload = req.get_json()
    logger.info(
        f'HTTP Request to update task with name {task_name} with payload: {request_payload}'
    )

    # Verifies if task exists
    if not task_repository.is_registered(task_name):
        logger.info('Task not found')
        return jsonify({'Message': task_messages.not_found}), 404

    # Verifies if payload is valid
    if not _is_a_task(request_payload):
        logger.info('Incorrect parameters')
        return jsonify({'Message': task_messages.incorrect_parameters}), 400

    task_with_new_values: Task = Task(request_payload['name'],
                                      request_payload['description'],
                                      request_payload['status'].lower())

    # Verifies if there is a task with same name
    if task_repository.is_registered(
            task_with_new_values.name
    ) and task_with_new_values.name != task_name:
        logger.info('Duplicated task name')
        return jsonify({'Message': task_messages.duplicated}), 400

    # Verifies if payload "status" is valid
    if not _is_status_valid(task_with_new_values.status):
        logger.info('Invalid status')
        return jsonify({'Message': task_messages.invalid_status}), 400

    # Updates the task!
    task_repository.update(task_name, task_with_new_values)
    logger.info('Task updated')
    return jsonify({'Message': task_messages.updated}), 200
コード例 #13
0
def handle_req(req: request, translate: bool) -> Any:
    """
    Handles common tasks for both validate and translate routes

    :param req: request
    :param translate: bool
    :return: json
    """
    if req.data:
        req_object = req.get_json()
        if 'pattern' not in req_object:
            raise InvalidUsage('Pattern is required', status_code=400)
        pattern = req_object['pattern']
        response = process_sigma(pattern, translate)
        return jsonify(response)
    else:
        raise InvalidUsage('No Request Data', status_code=400)
コード例 #14
0
def json_payload(request: flask.request) -> dict:
    """

    Args:
        request:

    Returns:

    """
    try:
        request_payload = request.get_json()
    except BadRequest:
        raise ValueError("JSON payload contains syntax errors. Please fix and try again.")

    if request_payload is None:
        raise ValueError("No JSON payload present. Make sure that the appropriate `content-type` "
                         "header is included in your request.")

    return request_payload
コード例 #15
0
ファイル: localization.py プロジェクト: 6a/jstanton.io.old
def get_lang_strings(in_request_args: request) -> dict:
    '''
    Takes a request arg dict (request.url) and identifies the appropriate query params and language identifier.

    Returns a dictionary that looks something like this:

    {
        lang: 'EN'
        query_param: ''
        query_param_toggle: 'lang=JP'
    }
    '''

    output_dictionary = {}

    output_dictionary['lang'] = sanitize_lang_string(in_request_args.get('lang'))
    output_dictionary['query_param'] = '' if output_dictionary['lang'] == STR_EN else JP_QUERY_PARAMS
    output_dictionary['query_param_toggle'] = '' if output_dictionary['query_param'] == JP_QUERY_PARAMS else JP_QUERY_PARAMS

    return output_dictionary
コード例 #16
0
def json_payload(request: flask.request) -> dict:
    """
    Verify that a payload exists and no syntax errors
    Args:
        request:

    Returns:

    Raises:
       ValueError:
    """
    try:
        request_payload = request.get_json()
    except BadRequest:
        raise ValueError("JSON payload contains syntax errors.")

    if request_payload is None:
        raise ValueError("No JSON payload present. Make sure that "
                         "'application/json' content-type header is included "
                         "in your request.")

    return request_payload
コード例 #17
0
def normalize_input_params(r: request) -> dict:
    # first check if this is JSON
    if r.is_json:
        try:
            return r.get_json()
        except BadRequest as br:
            print('Could not Parse JSON input')
            raise BadRequest('Could not parse JSON input!')

    # not JSON, check for URL form encoded
    else:
        print('no json here')
        form_dict = r.form.to_dict()
        if len(form_dict) == 1:
            # we have a dict it only contains a single thing
            first_key = list(form_dict)[0]
            first_val = form_dict[first_key]
            print(first_key)
            print(first_val)
            if first_val == '':
                # there is no value here, maybe the user supplied JSON with the wront content-type?
                # this can look like {'{"k":"v"}':''}
                try:
                    data = json.loads(first_key)
                    print(
                        'JSON data with url-form-encoded content-type detected'
                    )
                    return data
                except ValueError as ve:
                    # nope, not JSON - bail out here
                    print(
                        'Input was not key value pairs and not valid JSON! Bailing out'
                    )
                    raise RequiredParametersError(
                        'Not all required keys are present')

        # default to return the form_dict here
        return form_dict
コード例 #18
0
def add(req: request):
    """
    Adds a new task.

    It may return 400 if payload does not contain the necessary fields (name, description and status).
    It may return 400 if payload contains the name of a task that is already registered.
    It may return 400 if payload contains status with invalid value.
    If everything goes well, it returns 201.
    """
    logger.info(f'HTTP Request to add a new task with data: {req}')
    request_payload = req.get_json()
    logger.info(
        f'HTTP Request to add a new task with payload: {request_payload}')

    # Verifies if payload is valid
    if not _is_a_task(request_payload):
        logger.info('Incorrect parameters')
        return jsonify({'Message': task_messages.incorrect_parameters}), 400

    new_task: Task = Task(request_payload['name'],
                          request_payload['description'],
                          request_payload['status'].lower())

    # Verifies if there is a task with same name
    if task_repository.is_registered(new_task.name):
        logger.info('Duplicated task name')
        return jsonify({'Message': task_messages.duplicated}), 400

    # Verifies if payload "status" is valid
    if not _is_status_valid(new_task.status):
        logger.info('Invalid status')
        return jsonify({'Message': task_messages.invalid_status}), 400

    # Creates the task!
    task_repository.insert(new_task)
    logger.info('Task created')
    return jsonify({'Message': task_messages.created}), 201
コード例 #19
0
def persist_request(directory: str, req: request) -> Path:
    vname = "video_%d.mp4" % randint(0, 999999999999)
    vname_path = Path(directory, vname)
    with open(vname_path, 'wb') as f:
        f.write(req.get_data())
    return vname_path