Beispiel #1
0
    def validate_object(self, key, value_schema, value):
        if not isinstance(value, dict):
            raise ValidationError(
                "Field '%s' is of type 'object', received '%s' (%s)" %
                (key, str(value), type(value)))

        if not value_schema.get("properties"):
            # no validation on this object
            return

        for subkey, subvalue in value_schema["properties"].items():
            if subkey in value:
                self.validate_field(subkey, subvalue, value[subkey])
            elif subvalue.get("required", False) and not self._from_find:
                # if the field is required and we haven't pulled from find,
                # throw an exception
                raise ValidationError("Field '%s' is required but not found!" %
                                      subkey)

        # Check for additional properties
        if not value_schema.get("additionalProperties", True):
            extra = set(value.keys()) - set(value_schema["properties"].keys())

            if len(extra) > 0:
                raise ValidationError(
                    "Additional properties are not allowed: %s" %
                    ', '.join(list(extra)))
Beispiel #2
0
def new_post():
    json_post = request.json
    title = json_post.get('title')
    body = json_post.get('body')
    tags = json_post.get('tags')
    photos = json_post.get('nameList')
    if body is None or body == '':
        raise ValidationError('post does not have a body')
    if title is None or title == '':
        raise ValidationError('post does not have a title')
    post = Post(title=title, body=body)
    if tags:
        for name in re.split('[,,]', tags):
            tag = Tag.query.filter_by(name=name).first()
            if tag is None:
                tag = Tag(name=name)
                db.session.add(tag)
                db.session.commit()
            post.tags.append(tag)
    if photos:
        for name in photos:
            photo = Photo(name=name)
            db.session.add(photo)
            db.session.commit()
            post.photos.append(photo)
    db.session.add(post)
    db.session.commit()
    response = jsonify(Post.to_json(post))
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_post',
                                           id=post.id,
                                           _external=True)
    return response
Beispiel #3
0
 def f(value, field=None):
     if len(value) < min_:
         raise ValidationError(
             _('Value must be at least %d characters long') % min_)
     if max_ is not None and len(value) > max_:
         raise ValidationError(
             _('Value must be no more than %d characters long') % max_)
Beispiel #4
0
def validateCadastro(pedido, n_simafic, qtd_items):
    success = True
    error = "Dados Incorretos!"
    if not (len(pedido) <= 7 and patternPedido.match(pedido)):
        success = False
        raise ValidationError(
            "O pedido só pode conter números e no máximo 10 digitos!", error)
        pass
    if not (patternSimafic.match(n_simafic)):
        raise ValidationError(
            "Código SIMAFIC [{}] está fora do formato padrão!".format(
                n_simafic), error)
        success = False
        pass
    if not (len(qtd_items) < 10 and qtd_items.isdigit()):
        raise ValidationError(
            "O campo quantidade só pode contar numeros e no máximo 10 digitos.",
            error)
        success = False
        pass
    if (not validaSimaficXLS(n_simafic)):
        raise ValidationError("Código SIMAFIC não encontrado na planilha.",
                              "Simafic Incorreto!")
        success = False
        pass
    return success
Beispiel #5
0
def new_comment_reply(id):
    json_reply = request.json
    try:
        body = json_reply.get('body')
        to = json_reply.get('to')
    except AttributeError:
        raise ValidationError('wrong format')
    if body is None or body == '':
        raise ValidationError('reply does not have a body or receiver')
    if to is None or to == '':
        raise ValidationError('reply does not have a receiver')
    reply = Reply(body=body)
    reply.to = to
    comment = Comment.query.get_or_404(id)
    reply.comment = comment
    if g.current_user:
        reply.author = g.current_user.username
        reply.from_admin = True
    else:
        try:
            author = json_reply.get('author')
        except AttributeError:
            raise ValidationError('reply does not have a author')
        if author is None or reply == '':
            raise ValidationError('reply does not have a author')
        reply.author = author
        to_admin = json_reply.get('to_admin', False)
        if to_admin:
            reply.is_read=False
    db.session.add(reply)
    db.session.commit()
    response = jsonify(reply.to_json())
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_comment_replies', id=comment.id, _external=True)
    return response
Beispiel #6
0
    def _validate(self, payload, key=None):
        """helper function, gives a payload and validate the format

        either raise an exception or do nothing.

        Optional: key, only validate if the payload
        can fill into key value pair
        """
        if not self.validator:
            return  # no validation required
        if not key:
            # validates the whole payload
            try:
                if isinstance(self.validator, list):  # a list of keys
                    for key in self.validator:
                        if not (key in payload):
                            raise Exception()
                else:  # dict. key: payload keys, value: type
                    # Check instance type matchs
                    for key in self.validator:
                        if (not (key in payload)) or (not isinstance(
                                payload[key], self.validator[key])):
                            raise Exception()
            except:
                raise ValidationError(
                    'Wrong payload format: p:{}, v:{}'.format(
                        payload, self.validator))
        else:
            # only validate for key pair
            if isinstance(self.validator, dict):
                if key in self.validator and (not isinstance(
                        payload, self.validator[key])):
                    raise ValidationError(
                        'Wrong value format for key. K: {}, format: {}'.format(
                            payload, self.validator[key]))
Beispiel #7
0
def validate_instructor_nb(nb_file):
    """Ensures there is at least one BEGIN SOLUTION TAG in uploaded nb
    
    Should prevent accidentally uploading a student NB
    """

    solution_text = "BEGIN SOLUTION"
    found = False

    raw = nb_file.file.read()
    nb_file.file.seek(0)

    try:
        # TODO: as_verion = 4? should this come from the nb somehow?
        nb = nbformat.reads(raw, as_version=4)

    except Exception as e:
        log.exception(e)
        raise ValidationError(str(e))

    for cell in nb['cells']:
        if solution_text in cell['source']:
            log.info("Found solution cell")
            return

    raise ValidationError("No Solution Cells Found in uploaded notebook!"\
            " Are you sure this is the instructor version?")
Beispiel #8
0
def new_post_comment(id):
    json_comment = request.json
    try:
        body = json_comment.get('body')
    except AttributeError:
        raise ValidationError('comment does not have a body')
    if body is None or body == '':
        raise ValidationError('comment does not have a body')
    comment = Comment(body=body)
    post = Post.query.get_or_404(id)
    comment.post = post
    comment.floor = len(post.comments)
    if g.current_user:
        comment.author = g.current_user.username
        comment.is_read = True
        comment.from_admin = True
    else:
        try:
            author = json_comment.get('author')
        except AttributeError:
            raise ValidationError('comment does not have a author')
        if author is None or author == '':
            raise ValidationError('comment does not have a author')
        comment.author = author
    db.session.add(comment)
    db.session.commit()
    response = jsonify(comment.to_json())
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_post_comments',
                                           id=post.id,
                                           _external=True)
    return response
Beispiel #9
0
    def validate_simple(self, key, value_type, value):
        ''' Validate a simple field (not an object or array) against a schema. '''
        if value_type == "any":
            # can be anything
            pass
        elif value_type == "number" or value_type == "integer":
            # special case: can be an int or a float
            valid_types = [int, float, long]
            matches = [
                klass for klass in valid_types if isinstance(value, klass)
            ]

            if len(matches) == 0:
                raise ValidationError(
                    "Field '%s' is of type '%s', received '%s' (%s)" %
                    (key, value_type, str(value), type(value)))
        elif value_type in ValidTypes:
            if not isinstance(value, ValidTypes[value_type]):
                raise ValidationError(
                    "Field '%s' is of type '%s', received '%s' (%s)" %
                    (key, value_type, str(value), type(value)))
            # TODO: check other things like maximum, etc.
        else:
            # unknown type
            raise InvalidSchemaException("Unknown type '%s'!" % value_type)
Beispiel #10
0
    def validate(self, data: Dict):
        super(Policy, self).validate(data)

        effect = data.get('effect')
        action = data.get('action')
        resource = data.get('resource')

        if effect not in ['allow', 'deny']:
            raise ValidationError(
                message=f'unsupported effect "{effect}"'
            )

        if action != '*' and int(action) not in [action.value for action in ActionTypes]:
            raise ValidationError(
                message=f'unsupported action "{action}"'
            )

        if resource != '*':
            resource_obj = next(
                (resource for resource in Resource.get(filters={'name': [resource]})),
                None
            )

            if not resource_obj:
                raise ValidationError(
                    message=f'Resource Not Found "{resource}"'
                )
Beispiel #11
0
 def validate(self, value):
     if value is None and self.required:
         raise ValidationError('Field is required')
     if value or isinstance(value, bool):
         if not type(value) == int:
             raise ValidationError('Gender must contain only numbers')
         if value not in GENDERS:
             raise ValidationError(f'Gender must contain only numbers from: {prettify_dict(GENDERS)}')
Beispiel #12
0
def confirm_email(current_user, confirmation_key):
    if current_user.email_confirmed:
        raise ValidationError("Email already confirmed")
    if current_user.email_confirmation_key == confirmation_key:
        current_user.email_confirmed = True
        current_user.save()
    else:
        raise ValidationError("Invalid confirmation key!")
Beispiel #13
0
    def validate(self, value):
        if not (value or self.nullable):
            raise ValidationError('field "{}" cannot be empty'.format(
                self.name))

        if not isinstance(value, self.type):
            raise ValidationError('field "{}", invalid type "{}"'.format(
                self.name, self.type))
Beispiel #14
0
 def f(value, field=None):
     if len(value) < min_:
         raise ValidationError(
             _('Value must be at least %(min)d characters long') %
             {'min': min_})
     if max_ is not None and len(value) > max_:
         raise ValidationError(
             _('Value must be no more than %(max)d characters long') %
             {'max': max_})
Beispiel #15
0
    def validate(self, value):
        if not isinstance(value, self.type):
            raise ValidationError('invalid value type of field "gender"')

        if not value and value != UNKNOWN and not self.nullable:
            ValidationError('field "gender" cannot be empty')

        if value not in GENDERS:
            raise ValidationError('invalid value of field "gender"')
Beispiel #16
0
 def validate(self, value):
     super().validate(value)
     if value or isinstance(value, bool):
         if not type(value) in (int, str):
             raise ValidationError('Phone must be a string or number')
         if len(str(value)) != self.number_length:
             raise ValidationError(f'Phone length must be {self.number_length}')
         if not str(value).startswith('7'):
             raise ValidationError('Phone must start with 7')
Beispiel #17
0
 def __init__(self, value, suit):
     """Initializes a card"""
     if value not in CARD_VALUES:
         raise ValidationError(
             message='Card value {value} is invalid'.format(value=value))
     if suit not in CARD_SUITS:
         raise ValidationError(message='Card suit {suit} is invalid'.format(
             suit=suit))
     self.value = value
     self.suit = suit
Beispiel #18
0
    def check_user_input_keys(cls, deserialized_json):
        # Check if deserialized_json only contains valid keys.
        for key in cls.REQUIRED_FIELDS:
            if key not in deserialized_json:
                raise ValidationError(f'Field "{key}" is required.')

        # Check if all the fields are allowed.
        for key in deserialized_json:
            if key not in cls.ALLOWED_FIELDS:
                raise ValidationError(f'Field "{key}" is not allowed.')
Beispiel #19
0
def validate(username,
             email,
             password,
             background,
             country,
             tshirt_size=None,
             gender=None):
    if not email or "." not in email or "@" not in email:
        raise ValidationError("You must have a valid email!")

    if not utils.email.is_valid_email(email):
        raise ValidationError("You're lying")

    if background not in utils.select.BackgroundKeys:
        raise ValidationError("Invalid Background")

    if country not in utils.select.CountryKeys:
        raise ValidationError("Invalid Background")

    if tshirt_size and (tshirt_size not in utils.select.TShirts):
        raise ValidationError("Invalid T-shirt size")

    if gender and (gender not in ["M", "F"]):
        raise ValidationError("Invalid gender")

    if password is not None:
        if len(password) < 6:
            raise ValidationError("Password is too short.")
    if username is not None:
        if not username or len(username) > 50:
            raise ValidationError("Invalid username")
        if get_user(username=username):
            raise ValidationError("That username has already been taken.")
Beispiel #20
0
    def validate(self, value):
        super(BirthDayField, self).validate(value)

        if value:
            try:
                value = datetime.strptime(value, DATE_FORMAT).date()
            except ValueError:
                raise ValidationError('invalid date format')

            if (value + relativedelta(years=70)) < datetime.now().date():
                raise ValidationError('too old')
Beispiel #21
0
def validate_products_offset(offset):
    result = None
    
    if offset.isnumeric():
        if int(offset) < 0:
            raise ValidationError("OFFSET_CANNOT_BE_A_NEGATIVE_NUMBER")# 음수 금지
        result = int(offset)
    else:
        raise ValidationError("OFFSET_MUST_BE_AN_INTEGER")

    return result
Beispiel #22
0
    def __init__(self, email, password, access_level=0):

        if not self.is_mail_correct(email):
            raise ValidationError('This email address seems to be incorrect')

        if not self.is_password_strong(password):
            raise ValidationError('The password is not strong enough')

        self.email = email
        self.access_level = access_level
        self.pass_hash = security.generate_secret_hash(password)
Beispiel #23
0
 def from_json( json_post ):
     '''
     从 JSON 格式数据创建一篇博客文章
     '''
     body = json_post.get('body')
     title = json_post.get('title')
     if body is None or body == '':
         raise ValidationError('post does not have a body')
     if title is None or title == '':
         raise ValidationError('post does not have a title')
     return Post( body=body,title=title )
Beispiel #24
0
def validate_string(value, min_length=None, max_length=None):
    try:
        value = str(value)
    except ValueError:
        raise ValidationError('Not a string.')

    if ((min_length is not None and len(value) < min_length)
            or (max_length is not None and len(value) > max_length)):
        raise ValidationError('Invalid value.')

    return value
Beispiel #25
0
def validate_products_is_sold(is_sold):
    result = None

    if is_sold:
        if is_sold.isnumeric():
            is_sold = int(is_sold)
            if is_sold != 0 and is_sold != 1:
                raise ValidationError("IS_SOLD_MUST_BE_IN_[0, 1, None]")
        else:
            raise ValidationError("IS_SOLD_CANNOT_BE_A_STRING")
    return result
Beispiel #26
0
def validate_products_is_discounted(is_discounted):
    result = None

    if is_discounted:
        if is_discounted.isnumeric():
            is_discounted = int(is_discounted)
            if is_discounted != 0 and is_discounted != 1:
                raise ValidationError("IS_DISCOUNTED_MUST_BE_IN_[0, 1, None]")
        else:
            raise ValidationError("IS_DISCOUNTED_CANNOT_BE_A_STRING")
    return result
Beispiel #27
0
 def __init__(self, player_count):
     self.hands = []
     if player_count < 2:
         raise ValidationError('Not enough players - Minimum is 2')
     if player_count > 10:
         raise ValidationError('Too many players - Maximum is 10')
     self.deck = [
         Card(value, suit) for value in CARD_VALUES for suit in CARD_SUITS
     ]
     random.shuffle(self.deck)
     for player in range(player_count):
         self.hands.append(self.draw_hand())
Beispiel #28
0
def validateInfoScan(responsavel, caixa, pedido):
    success = True
    error = "Dados Incorretos!"
    if not (responsavel):
        success = False
        raise ValidationError(
            "O Campo [Responsável pela contagem] deve ser preenchido.", error)
    if not caixa:
        success = False
        raise ValidationError("O Campo [Numero da Caixa] deve ser preenchido.",
                              error)
    return success
Beispiel #29
0
def validate_products_product_id(product_id):
    result = None

    if product_id:
        if product_id.isnumeric():
            if int(product_id) < 1:
                raise ValidationError("PRODUCT_ID_MUST_BE_GREATER_THAN_1")
            result = int(product_id)
        else:
            raise ValidationError("PRODUCT_ID_MUST_BE_A_NUMBER")

    return result
Beispiel #30
0
def reset_password(token, password):
    if len(password) < 6:
        raise ValidationError("Password is too short!")
    try:
        user = User.get(User.password_reset_token == token)
        if user.password_reset_expired < datetime.now():
            raise ValidationError("Token expired")
        user.set_password(password)
        user.password_reset_token = None
        user.save()
    except User.DoesNotExist:
        raise ValidationError("Invalid reset token!")
Beispiel #31
0
def properties_draft3(validator, properties, instance, schema):
    if not validator.is_type(instance, "object"):
        return

    for property, subschema in iteritems(properties):
        if property in instance:
            for error in validator.descend(
                instance[property],
                subschema,
                path=property,
                schema_path=property,
            ):
                yield error
        elif subschema.get("required", False):
            error = ValidationError("%r is a required property" % property)
            error._set(
                validator="required",
                validator_value=subschema["required"],
                instance=instance,
                schema=schema,
            )
            error.path.appendleft(property)
            error.schema_path.extend([property, "required"])
            yield error