Exemple #1
0
 def validator(value):
     if min is not None and value < min:
         raise ValidationError('%s is less than minimum value of %s.' %
                               (value, min))
     if max is not None and value > max:
         raise ValidationError('%s is greater than maximum value of %s.' %
                               (value, max))
Exemple #2
0
def validator_ws_uri(value):
    """Validate if the value is a valid ws/wss uri."""
    DOMAIN_PATTERN = re.compile(
        r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
        r'(?:[A-Z]{2, 6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)'  # domain
        r'(?::\d+)?\Z',  # optional port
        re.IGNORECASE
    )
    PATH_PATTERN = re.compile(r'\A\S*\Z')

    scheme, rest = value.split('://')

    if scheme.lower() not in ['ws', 'wss']:
        raise ValidationError('Unrecognized scheme: ' + scheme)

    domain, _, path = rest.partition('/')

    if not PATH_PATTERN.match(path):
        raise ValidationError('Invalid path: ' + path)

    if not DOMAIN_PATTERN.match(domain):
        # Check if it is an IP address
        try:
            ipaddress.ip_address(domain)
        except ValueError:
            try:
                # Check if there's a port. Remove it, and try again.
                domain, port = domain.rsplit(':', 1)
                ipaddress.ip_address(domain)
            except ValueError:
                raise ValidationError('Invalid URL: ' + rest)
Exemple #3
0
    def clean_fields(self, exclude=None):
        """Validate the values of all fields.

        This method will raise a :exc:`~pymodm.errors.ValidationError` that
        describes all issues with each field, if any field fails to pass
        validation.

        :parameters:
          - `exclude`: A list of fields to exclude from validation.

        """
        exclude = validate_list_tuple_or_none('exclude', exclude)
        exclude = set(exclude) if exclude else set()
        error_dict = {}
        for field in self._mongometa.get_fields():
            if field.attname in exclude:
                continue
            try:
                field_value = field.value_from_object(self)
                field_empty = field.is_undefined(self)
                if field_empty and field.required:
                    error_dict[field.attname] = [
                        ValidationError('field is required.')
                    ]
                elif not field_empty:
                    field.validate(field_value)
            except Exception as exc:
                error_dict[field.attname] = [ValidationError(exc)]
        if error_dict:
            raise ValidationError(error_dict)
Exemple #4
0
def validate_mentor(user_id):
    user = User.objects.get({'_id': user_id})
    if user:
        if not user.role == 'mentor':
            raise ValidationError('Given user is not a mentor')
    else:
        raise ValidationError('Mentor ID is invalid.')
Exemple #5
0
def validate_mentor(user_id):
    user = User.objects.get({'_id': user_id})
    if user:
        # code.interact(local=dict(globals(), **locals()))
        if not user.role == 'mentor':
            raise ValidationError('Given user is not a mentor')
    else:
        raise ValidationError('Mentor ID is invalid.')
Exemple #6
0
 def validator(value):
     len_value = len(value)
     if min is not None and len_value < min:
         raise ValidationError('%s is under the minimum length of %d.' %
                               (value, min))
     if max is not None and len_value > max:
         raise ValidationError('value exceeds the maximum length of %d.' %
                               (max, ))
Exemple #7
0
 def validate_related_model(value):
     if not isinstance(value, list):
         raise ValidationError('%r must be a list.' % value)
     for v in value:
         if not isinstance(v, self.related_model):
             raise ValidationError('%r is not an instance of %s.' %
                                   (v, self.related_model.__name__))
         v.full_clean()
Exemple #8
0
 def validate_keys(value):
     for key in value:
         if not isinstance(key, string_types):
             raise ValidationError(
                 'All dictionary keys must be strings: %r' % value)
         if '.' in key or '$' in key:
             raise ValidationError(
                 'Dictionary keys must not contain "$" or ".": %r' %
                 value)
Exemple #9
0
 def validate_type(self):
     if self.type_ != None:
         if self.type_ == 'multiple' and len(self.members) < 2:
             raise ValidationError(
                 "Atleast two members are required to start a multiple session."
             )
         if self.type_ == 'single' and len(self.members) > 1:
             raise ValidationError(
                 "Only one member is allowed in single mode.")
Exemple #10
0
def validate_users(user_ids):
    try:
        for id_ in user_ids:
            user = User.objects.get({"_id": ObjectId(id_)})
            if not user.role == 'student':
                raise ValidationError('Given user/users is not a student')
    except Exception as e:
        message = "User does not exists." if str(e) == "" else str(e)
        raise ValidationError(message)
Exemple #11
0
 def set_role(self, role: GroupRole):
     if not role:
         raise ValidationError("Необходимо указать id роли")
     if self.role_id:
         raise ValidationError("Роль уже задана")
     if not self.group_id:
         raise ValidationError(
             "Перед установкой роли необходимо задать группу")
     self.role_id = role.pk
     self.save()
 def _validate_choices(self, value):
     # Is self.choices a list of pairs? A flat list?
     if isinstance(self.choices[0], (list, tuple)):
         flat_choices = [pair[0] for pair in self.choices]
         if value not in flat_choices:
             raise ValidationError('%r is not a choice. Choices are %r.' %
                                   (value, flat_choices))
     elif value not in self.choices:
         raise ValidationError('%r is not a choice. Choices are %r.' %
                               (value, self.choices))
Exemple #13
0
def validate_sessions(session_ids):
    try:
        # code.interact(local=dict(globals(), **locals()))
        for id_ in session_ids:
            session = Session.objects.get({"_id": ObjectId(id_)})
            if not session:
                raise ValidationError('Not a session')
    except Exception as e:
        message = "Session does not exists." if str(e) == "" else str(e)
        raise ValidationError(message)
Exemple #14
0
 def clean(self):
     if self.role_id:
         target_group = Group.objects.get({"_id": self.group_id.pk})
         if self.role_id not in target_group.role_list:
             raise ValidationError("Группа %s не предусматривает роль %s" %
                                   (target_group.name, self.role_id.name))
     if [
             x for n, x in enumerate(self.permissions)
             if x in self.permissions[:n]
     ]:
         raise ValidationError("Разрешения не должны повторяться")
Exemple #15
0
def _mode_validation(key, value):
    if not isinstance(value, dict) or len(value) != 3 or not all(k in value.keys() for k in _REQUIRED_MODE_KEYS):
        raise ValidationError(
            'field must have {} key with value dict of length 3 and keys {}.'.format(key, _REQUIRED_MODE_KEYS))

    dist_dur = _REQUIRED_MODE_KEYS[:2]
    for key in dist_dur:
        _dist_dur_validation(key, value[key])

    show = value[_REQUIRED_MODE_KEYS[2]]
    if not isinstance(show, bool):
        raise ValidationError('field show in {} must be a boolean'.format(key))
Exemple #16
0
 def validate_coordinates(coordinates):
     try:
         coordinates[0][0]
     except Exception:
         raise ValidationError('LineString must contain at least one Point.')
     errors = []
     for point in coordinates:
         try:
             PointField.validate_coordinates(point)
         except ValidationError as e:
             errors.append(e)
     if errors:
         raise ValidationError(errors)
Exemple #17
0
 def validate_coordinates(coordinates):
     try:
         coordinates[0][0][0][0]
     except Exception:
         raise ValidationError(
             'MultiPolygon must contain at least one Polygon.')
     errors = []
     for polygon in coordinates:
         try:
             PolygonField.validate_coordinates(polygon)
         except ValidationError as e:
             errors.append(e)
     if errors:
         raise ValidationError(errors)
Exemple #18
0
 def validate_coordinates(coordinates):
     try:
         coordinates[0][0][0]
     except Exception:
         raise ValidationError(
             'MultiLineString must contain at least one LineString.')
     errors = []
     for linestring in coordinates:
         try:
             LineStringField.validate_coordinates(linestring)
         except ValidationError as e:
             errors.append(e)
     if errors:
         raise ValidationError(errors)
Exemple #19
0
 def to_mongo(self, value):
     if isinstance(value, abc.Mapping):
         return value
     try:
         return dict(value)
     except ValueError as e:
         raise ValidationError(e)
Exemple #20
0
 def to_mongo(self, value):
     if isinstance(value, OrderedDict):
         return value
     try:
         return OrderedDict(value)
     except ValueError as e:
         raise ValidationError(e)
Exemple #21
0
 def to_mongo(self, value):
     if isinstance(value, uuid.UUID):
         return value
     try:
         return uuid.UUID(value)
     except ValueError as e:
         raise ValidationError(e)
Exemple #22
0
 def to_mongo(self, value):
     if isinstance(value, Code):
         return value
     try:
         return Code(value)
     except TypeError as e:
         raise ValidationError(e)
        def validate_ldatatype(value):

            try:
                self.DATA_TYPE(value)
            except ValueError:
                msg = '%r is not a valid %s.' % value, self.DATA_TYPE.__name__
                raise ValidationError(msg)
Exemple #24
0
 def to_mongo(self, value):
     if isinstance(value, Binary):
         return value
     try:
         return Binary(value, subtype=self.subtype)
     except (TypeError, ValueError) as exc:
         raise ValidationError(exc)
Exemple #25
0
 def to_mongo(cls, value):
     """Convert value for storage."""
     try:
         return str(EUI64(value))
     except ValueError:
         msg = '%r is not a valid EUID.' % value
         raise ValidationError(msg)
Exemple #26
0
 def to_python(cls, value):
     """Convert value back to Python."""
     try:
         return EUI64(value)
     except ValueError:
         msg = '%r is not a valid EUID.' % value
         raise ValidationError(msg)
Exemple #27
0
        def validate_plmnid(value):

            try:
                PLMNID(value)
            except ValueError:
                msg = '%r is not a valid PLMN id.' % value
                raise ValidationError(msg)
Exemple #28
0
        def validate_ssid(value):

            try:
                SSID(value)
            except ValueError:
                msg = '%r is not a valid SSID.' % value
                raise ValidationError(msg)
Exemple #29
0
        def validate_ethernet_address(value):

            try:
                EtherAddress(value)
            except ValueError:
                msg = '%r is not a valid Ethernet address.' % value
                raise ValidationError(msg)
Exemple #30
0
 def validate_coordinates(coordinates):
     if not (isinstance(coordinates,
                        (list, tuple)) and len(coordinates) == 2):
         raise ValidationError('Point is not a pair: %r' % coordinates)
     validate_number = validators.validator_for_type((float, int),
                                                     'coordinate value')
     validate_number(coordinates[0])
     validate_number(coordinates[1])