Example #1
0
def __user_agent_validator(user_agent: str) -> None:
    """
    Validates the user agent header.

    User agent specs: https://developer.mozilla.org/en-US/docs/Web/
        HTTP/Headers/User-Agent

    Enforce a minimum pattern of "uname/version".
    """
    trace_enter(inspect.currentframe())

    if len(user_agent) > 150:
        err_msg = 'User agent contains more than 150 characters.'
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)

    parts = user_agent.split('/')

    err_msg = 'User agent pattern does not match "name/version"'
    if len(parts) < 2:
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)

    if (len(parts[0]) < 1) or (len(parts[1]) < 1):
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)
Example #2
0
def deserialize_query_filter(value, value_type):
    value = value.strip()
    if len(value) == 0:
        raise ValidationError('empty value')
    if len(value) > 1 and ((value[0] == '"' and value[-1] == '"') or
                           (value[0] == '\'' and value[-1] == '\'')):
        operator = '$eq'
        value = value[1:-1]
        return {operator: value}
    elements = value.split(':')
    if len(elements) == 1:
        operator = '$eq'
        value = elements[0]
    elif len(elements) == 2:
        operator = '${}'.format(elements[0].lower())
        value = elements[1]
        if operator not in ['$eq', '$ne', '$gt', '$lt', '$gte', '$lte']:
            raise ValidationError('unknown operator')
    else:
        raise ValidationError('too many values')
    try:
        if value_type == int:
            value = int(value)
        elif value_type == float:
            value = float(value)
        elif value_type == str:
            if len(value) > 1 and ((value[0] == '"' and value[-1] == '"') or
                                   (value[0] == '\'' and value[-1] == '\'')):
                value = value[1:-1]
        else:
            raise ValidationError('unsupported value type')
    except:
        raise ValidationError('invalid value type')
    return {operator: value}
Example #3
0
def __x_real_ip_validator(x_real_ip: str) -> None:
    """Validates the X-Real-IP header."""
    trace_enter(inspect.currentframe())

    if not 6 < len(x_real_ip) < 16:
        err_msg = 'X-Real-Ip must be between 7 and 15 characters long.'
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)

    parts = x_real_ip.split('.')

    if len(parts) != 4:
        err_msg = ('X-Real-Ip format does not match: '
                   'digits.digits.digits.digits.')
        logger.error(err_msg)
        trace_exit(inspect.currentframe(), err_msg)
        raise ValidationError(err_msg, status_code=422)

    for part in parts:
        if not 0 < len(part) < 4:
            err_msg = ('X-Real-Ip format does not match: '
                       'x.x.x.x-xxx.xxx.xxx.xxx')
            logger.error(err_msg)
            trace_exit(inspect.currentframe(), err_msg)
            raise ValidationError(err_msg, status_code=422)
Example #4
0
def validate_integer_string_list(field):
    validate_query_string(field)
    for num in split_re.split(field):
        if num and not is_digit(num.strip()):
            raise ValidationError('Not a valid coma-separated list of integers')

    if len(split_re.split(field)) > MAX_LIMIT:
        raise ValidationError('Request Entity Too Large')
Example #5
0
def deserialize_query_last(value):
    elements = value.strip().split(':')
    if len(elements) == 0:
        raise ValidationError('empty value')
    objectid = elements[-1]
    if len(objectid) != 24 or any(c not in string.hexdigits for c in objectid):
        raise ValidationError('invalid value')
    return elements
Example #6
0
 def _validate(self, value):
     super()._validate(value)
     try:
         value = int(value)
     except (TypeError, ValueError):
         raise ValidationError('District must be a number')
     if value < 0:
         raise ValidationError('District must be a natural number')
Example #7
0
def validate_filter(val):
    if filter and not filter_to_index_mapping:
        raise ValidationError("This api does not accept filter. Please update your model.")
    keys = [*filter_to_index_mapping]
    if filter and any(x not in keys for x in val):
        if len(keys) < 11:
            raise ValidationError(f"Invalid value. Options are: {', '.join(keys)}")
        raise ValidationError("Invalid value.")
Example #8
0
 def _deserialize(self, value, attr, data, **kwargs):
     if isinstance(value, str):
         try:
             return SimpleEncrypt.decrypt(value)
         except Exception as e:
             raise ValidationError("decrypt password fail")
     else:
         raise ValidationError("value type error")
Example #9
0
    def _deserialize(self, value, attr, data, **kwargs):
        if not isinstance(value, str):
            raise ValidationError(f"{attr} has to be a string")
        try:
            int_value = int(value)
        except ValueError:
            raise ValidationError("Could not parse integer")

        return int_value
Example #10
0
def test_handle_error_called_when_parsing_raises_error(parse_json, handle_error, web_request):
    val_err = ValidationError('error occurred')
    parse_json.side_effect = val_err
    p = Parser()
    p.parse({'foo': fields.Field()}, web_request, locations=('json',))
    handle_error.assert_called
    parse_json.side_effect = ValidationError('another exception')
    p.parse({'foo': fields.Field()}, web_request, locations=('json',))
    assert handle_error.call_count == 2
Example #11
0
 def _deserialize(self, value, attr, data, **kwargs):
     if isinstance(value, dict):
         return value
     elif isinstance(value, str):
         try:
             return json.loads(value)
         except Exception as e:
             raise ValidationError("value error must json str")
     else:
         raise ValidationError("value type error")
Example #12
0
def validate_query_string(field):
    if DISALLOWED_CHARACTERS.search(field):
        raise ValidationError('Disallowed character detected')
    try:
        field.decode('ascii')
    except UnicodeDecodeError:
        raise ValidationError('Disallowed encoding of request string')

    if len(field) and len(field.strip()) == 0:
        raise ValidationError('Empty request string. Only Space character not allowed in string.')
Example #13
0
def validate_query(parsed_fields, all_fields):
  for key, value in request.args.items():
    if key not in all_fields:
      raise ValidationError({key: ['Unknown parameter.']})

  if 'start' in parsed_fields and 'stop' in parsed_fields:
    if parsed_fields['stop'] <= parsed_fields['start']:
      raise ValidationError({'start': ['Start position must be greater than stop position.']})

  return True
Example #14
0
def validate_coordinates(coordinates):
    """Ensure that coordinates number two and are within the legal range."""
    if not len(coordinates) == 2:
        raise ValidationError(
            "Coordinates list must contain exactly two floats.")
    lat = coordinates[0]
    if not (-90 <= lat <= 90):
        raise ValidationError("Latitude must be between -90 and 90")
    lng = coordinates[1]
    if not (-180 <= lng <= 180):
        raise ValidationError("Longitude must be between -180 and 180")
Example #15
0
 def _deserialize(self, value, attr, data, **kwargs):
     if not (isinstance(value, str) and value.startswith("0x")):
         raise ValidationError(
             f"Could not parse hex-encoded bytes objects of attribute {attr}: {value}"
         )
     try:
         # Create bytes first, to not use weird conversion done by hexbytes constructor
         return hexbytes.HexBytes(bytes.fromhex(value[2:]))
     except ValueError:
         raise ValidationError(
             f"Could not parse hex-encoded bytes objects of attribute {attr}: {value}"
         )
Example #16
0
    def check_publisher(self, data, **_):  # noqa
        role = data['role']
        publisher_id = data['publisher_id']

        if role == ROLE_MANAGER and not publisher_id:
            raise ValidationError(
                f'Required for role {ROLE_MANAGER}',
                field_name='publisher_id',
            )

        if role == ROLE_ADMIN and publisher_id:
            raise ValidationError(
                f'Shouldn\'t be filled for role {ROLE_ADMIN}',
                field_name='publisher_id',
            )
Example #17
0
 def __call__(self, value):
     for sort_column in value:
         if sort_column.lstrip('-') not in self.values:
             raise ValidationError(
                 'Cannot sort on value "{0}"'.format(value),
                 status_code=422
             )
Example #18
0
    def _serialize(self, value, attr, obj, **kwargs):

        if isinstance(value, MetaTransaction.OperationType):
            # serialises into the value of the OperationType enum
            return value.value
        else:
            raise ValidationError("Value must be of type OperationType")
Example #19
0
    def _deserialize(self, value, attr, data, **kwargs):
        if not isinstance(value, str) or not re.match(r"0x[0-9a-fA-F]{64}",
                                                      value):
            raise ValidationError(
                f"Could not parse attribute {attr}: Invalid hash {value}")

        return value
Example #20
0
def validate_json(val):
    """校验json格式"""
    try:
        print(val)
        json.loads(val)
    except ValueError:
        raise ValidationError("json格式错误")
Example #21
0
def user_exists(email):
    """Validate that a user exists."""
    try:
        profile = UserProfile.get_by_username(email)
    except NoResultFound:
        if not current_datastore.get_user(email):
            raise ValidationError('USER_DOES_NOT_EXIST')
Example #22
0
    def _serialize(self, value, attr, obj, **kwargs):

        if isinstance(value, FeePayer):
            # serialises into the value of the FeePayer enum
            return value.value
        else:
            raise ValidationError("Value must be of type FeePayer")
Example #23
0
def validate_age(dob):
    today = date.today()
    age = today.year - dob.year - ((today.month, today.day) <
                                   (dob.month, dob.day))
    if age > 18:
        return True
    raise ValidationError('Customer age must be greater than 18.')
Example #24
0
    def _deserialize(self, value, attr, data, **kwargs):
        try:
            hex_bytes = hexbytes.HexBytes(value)
        except ValueError:
            raise ValidationError("Could not parse Hex number")

        return hex_bytes
Example #25
0
    def _serialize(self, value, attr, obj, **kwargs):

        if isinstance(value, TransactionStatus):
            # serialises into the value of the TransactionStatus enum
            return value.value
        else:
            raise ValidationError(
                f"Value must be of type TransactionStatus: {value}")
Example #26
0
def validate_ip(val):
    """校验ip类型"""
    try:
        ip = ipaddress.ip_address(val)
        if ip.is_loopback or ip.is_multicast or ip.is_reserved:
            raise ValueError
    except ValueError as e:
        raise ValidationError("非法的IP地址")
Example #27
0
def validate_tag_name(val):
    consumer_tags = db.session.query(
        ConsumerTagsModel.tag_name.distinct().label('tag_name'))
    tag_type_list = [row.tag_name for row in consumer_tags.all()]
    if val in tag_type_list:
        return True
    raise ValidationError("Wrong tag type=%s. Please request for  =%s" %
                          (val, tag_type_list))
Example #28
0
    def _deserialize(self, value, attr, data, **kwargs):

        # deserialize into the FeePayer enum instance corresponding to the value
        try:
            return FeePayer(value)
        except ValueError:
            raise ValidationError(
                f"Could not parse attribute {attr}: {value} has to be one of "
                f"{[fee_payer.value for fee_payer in FeePayer]}")
Example #29
0
    def _deserialize(self, value, attr, data, **kwargs):

        # deserialize into the TransactionStatus enum instance corresponding to the value
        try:
            return MetaTransactionStatus(value)
        except ValueError:
            raise ValidationError(
                f"Could not parse attribute {attr}: {value} has to be one of "
                f"{[status.value for status in TransactionStatus]}")
Example #30
0
def deserialize_query_sort(value):
    query_sort = list()
    for key_direction in (x.strip().split(':')
                          for x in value.strip().split(',')):
        if len(key_direction) == 0 or len(key_direction) > 2:
            raise ValidationError('invalid sort syntax')
        key = key_direction[0].lower()
        if key not in allowed_sort_keys:
            raise ValidationError('sort is not supported for specified key(s)')
        direction = key_direction[1].lower() if len(key_direction) > 1 else ''
        if direction == '' or direction == 'asc' or direction == '1':
            direction = ASCENDING
        elif direction == 'desc' or direction == '-1':
            direction = DESCENDING
        else:
            raise ValidationError('unkown sort direction')
        query_sort.append((key, direction))
    return query_sort