Ejemplo n.º 1
0
class TextValidator:
	message = _('Введено недоступні символи.')
	code = 'invalid'
	text_regex = _lazy_re_compile(r"^[-!#$%& ',.\"*+/=?^_`{}\[\]|~0-9A-Z]+$", re.IGNORECASE)
	name_regex = _lazy_re_compile(r"^[-!#%& ',.\"*+/=?^_`{}\[\]|~0-9A-Z]+$", re.IGNORECASE)
	def __init__(self, message=None, code=None):
		if message is not None:
			self.message = message
		if code is not None:
			self.code = code

	def __call__(self, text, min, max, name):
		if (len(text) > max or min > len(text)) and max != -1:
			raise ValidationError(_('%s повинен(-на) бути %d-%d символів.' % (name,min,max)), code=self.code)
		if not self.text_regex.fullmatch(text):
			raise ValidationError(message=self.message, code=self.code)

	def ValidName(self, text, min, max, name):
		if (len(text) > max or min > len(text)) and max != -1:
			raise ValidationError(_('%s повинен(-на) бути %d-%d символів.' % (name,min,max)), code=self.code)
		if not self.name_regex.fullmatch(text):
			raise ValidationError(message=self.message, code=self.code)

	def __eq__(self, other):
		return (
			isinstance(other, TextValidator) and 
			(self.message == other.message) and
			(self.code == other.code)
		)
Ejemplo n.º 2
0
class PhoneValidator(object):
    message = u'Не верный формат номера телефона'
    code = 'invalid'
    code_city_regex = _lazy_re_compile(r'\d{3,5}')
    phone_number_regex = _lazy_re_compile(r'\d{5,7}')

    def __init__(self, message=None, code=None):
        if message is not None:
            self.message = message
        if code is not None:
            self.code = code

    def __call__(self, value):
        if not self.code_city_regex.match(self.find_all_numbers(value[1])):
            raise ValidationError(self.message, code=self.code)

        if not self.phone_number_regex.match(self.find_all_numbers(value[2])):
            raise ValidationError(self.message, code=self.code)

    def __eq__(self, other):
        return (isinstance(other, PhoneValidator)
                and (self.message == other.message)
                and (self.code == other.code))

    @staticmethod
    def find_all_numbers(value):
        return ''.join(re.findall('\d', value))
Ejemplo n.º 3
0
class NonStrictEmailValidator(validators.EmailValidator):
    user_regex = validators._lazy_re_compile(
        r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z"  # dot-atom
        r"|^[-!#$%&.'*+/=?^_`{}|~0-9A-Z]+\Z"  # docomoの古いアドレスなどである'.@'を許容する
        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'
        r'|\\[\001-\011\013\014\016-\177])*"\Z)',  # quoted-string
        re.IGNORECASE)
Ejemplo n.º 4
0
class Site(models.Model):

    resource_group = models.ForeignKey(ResourceGroup, related_name="sites")
    name = models.CharField(
        max_length=100,
        validators=[
            validators.RegexValidator(
                validators._lazy_re_compile(r"^[a-zA-Z0-9_-]+$"),
                "Invalid name. (hint: ^[a-zA-Z0-9_-]+$)",
            ),
        ])
    created = models.DateTimeField(default=timezone.now)

    objects = SiteManager()

    class Meta:
        unique_together = [("resource_group", "name")]

    def members(self):
        member_set = set()
        for member in self.resource_group.members():
            member.role = {
                "admin": "admin",
                "technical": "ops",
            }[member.role]
            member_set.add(member)
        for membership in SiteMembership.objects.filter(site=self):
            member = membership.user
            member.role = membership.role
            member_set.add(member)
        return member_set
Ejemplo n.º 5
0
class EnhancedURLValidator(URLValidator):
    """
    Extends Django's built-in URLValidator to permit the use of hostnames with no domain extension.
    """
    class AnyURLScheme(object):
        """
        A fake URL list which "contains" all scheme names abiding by the syntax defined in RFC 3986 section 3.1
        """
        def __contains__(self, item):
            if not item or not re.match(r'^[a-z][0-9a-z+\-.]*$', item.lower()):
                return False
            return True

    fqdn_re = URLValidator.hostname_re + URLValidator.domain_re + URLValidator.tld_re
    host_res = [
        URLValidator.ipv4_re, URLValidator.ipv6_re, fqdn_re,
        URLValidator.hostname_re
    ]
    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # Scheme (previously enforced by AnyURLScheme or schemes kwarg)
        r'(?:\S+(?::\S*)?@)?'  # HTTP basic authentication
        r'(?:' + '|'.join(host_res) + ')'  # IPv4, IPv6, FQDN, or hostname
        r'(?::\d{2,5})?'  # Port number
        r'(?:[/?#][^\s]*)?'  # Path
        r'\Z',
        re.IGNORECASE)
    schemes = AnyURLScheme()
Ejemplo n.º 6
0
class EnhancedURLValidator(URLValidator):
    """
    Extends Django's built-in URLValidator to permit the use of hostnames with no domain extension and enforce allowed
    schemes specified in the configuration.
    """
    fqdn_re = URLValidator.hostname_re + URLValidator.domain_re + URLValidator.tld_re
    host_res = [
        URLValidator.ipv4_re, URLValidator.ipv6_re, fqdn_re,
        URLValidator.hostname_re
    ]
    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # Scheme (enforced separately)
        r'(?:\S+(?::\S*)?@)?'  # HTTP basic authentication
        r'(?:' + '|'.join(host_res) + ')'  # IPv4, IPv6, FQDN, or hostname
        r'(?::\d{2,5})?'  # Port number
        r'(?:[/?#][^\s]*)?'  # Path
        r'\Z',
        re.IGNORECASE)
    schemes = None

    def __call__(self, value):
        if self.schemes is None:
            # We can't load the allowed schemes until the configuration has been initialized
            self.schemes = get_config().ALLOWED_URL_SCHEMES
        return super().__call__(value)
Ejemplo n.º 7
0
class LTreeLabelField(CharField):
    description = _("PostgreSQL ltree label (up to %(max_length)s)")

    default_validators = [
        RegexValidator(
            _lazy_re_compile(r'^[a-zA-Z0-9_]+\Z'),
            _("Enter a valid 'ltree label' consisting of letters, numbers or underscores."
              ), 'invalid')
    ]

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 255
        kwargs['editable'] = False
        kwargs['unique'] = True
        self.allow_unicode = False

        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()

        del kwargs['max_length']
        del kwargs['editable']
        del kwargs['unique']

        return name, path, args, kwargs
Ejemplo n.º 8
0
def validate_url(url, schemes=('http', 'https')):
    """Validator for URLs.

    Uses's django's URLValidator plumbing but isn't as restrictive and
    URLs of the form http://foo are considered valid.

    Built from:

    `https://docs.djangoproject.com/en/2.1/_modules/django/
        core/validators/#URLValidator`

    :param url: Input value for a url.
    :raise ValidationError: If the url is not valid.
    """
    # Re-structure django's regex.
    url_validator = URLValidator
    host_re = ('(' + url_validator.hostname_re + url_validator.domain_re +
               url_validator.tld_re + '|' + url_validator.hostname_re +
               '|localhost)')

    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
        r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
        r'(?:' + url_validator.ipv4_re + '|' + url_validator.ipv6_re + '|' +
        host_re + ')'
        r'(?::\d{2,5})?'  # port
        r'(?:[/?#][^\s]*)?'  # resource path
        r'\Z',
        re.IGNORECASE)

    url_validator.regex = regex
    valid_url = url_validator(schemes=schemes)

    # Validate the url.
    return valid_url(url)
Ejemplo n.º 9
0
class CustomURLValidator(URLValidator):
    ul = '\u00a1-\uffff'  # unicode letters range (must not be a raw string)

    # IP patterns
    ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
    ipv6_re = r'\[[0-9a-f:\.]+\]'  # (simple regex, validated later)

    # Host patterns
    hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
    domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
    tld_re = (
        r'\.'  # dot
        r'(?!-)'  # can't start with a dash
        r'(?:[a-z' + ul + '-]{2,63}'  # domain label
        r'|xn--[a-z0-9]{1,59})'  # or punycode label
        r'(?<!-)'  # can't end with a dash
        r'\.?'  # may have a trailing dot
    )
    host_re = '(' + hostname_re + domain_re + tld_re + ')'

    loopbacks = r'localhost|127(?:\.[0-9]+){0,2}\.[0-9]+|(?:0*\:)*?:?0*1'

    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
        r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
        r'(?!' + loopbacks + r')'  # exclude loopbacks
        r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')'
        r'(?::\d{2,5})?'  # port
        r'(?:[/?#][^\s]*)?'  # resource path
        r'\Z',
        re.IGNORECASE)
    schemes = ['http', 'https']
Ejemplo n.º 10
0
class ExtendedUrlValidator(validators.URLValidator):
    """
        Fully copied django default url validator, but allowed
        urls with additional schemas and without dots extensions.
        Django do not offer legal methods for partial overriding
        of url regexp validator 
    """
    schemes = ['http', 'https', 'ftp', 'ftps', 'tg']
    ul = '\u00a1-\uffff'  # unicode letters range (must not be a raw string)

    # IP patterns
    ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
    ipv6_re = r'\[[0-9a-f:\.]+\]'  # (simple regex, validated later)

    # Host patterns
    hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
    
    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
    domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
    tld_re = (
        r'\.?'                               # dot
        r'(?!-)'                             # can't start with a dash
        r'(?:[a-z' + ul + '-]{2,63}'         # domain label
        r'|xn--[a-z0-9]{1,59})'              # or punycode label
        r'(?<!-)'                            # can't end with a dash
        r'\.?'                               # may have a trailing dot
    )
    host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)'
    regex = validators._lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
        r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
        r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')'
        r'(?::\d{2,5})?'  # port
        r'(?:[/?#][^\s]*)?'  # resource path
        r'\Z', re.IGNORECASE)
Ejemplo n.º 11
0
class ResourceGroup(models.Model):

    name = models.CharField(
        max_length=100,
        unique=True,
        validators=[
            validators.RegexValidator(
                validators._lazy_re_compile(r"^[a-zA-Z0-9_-]+$"),
                "Invalid name. (hint: ^[a-zA-Z0-9_-]+$)",
            ),
        ])
    created = models.DateTimeField(default=timezone.now)

    objects = ResourceGroupManager()

    def __str__(self):
        return self.name

    def set_owner(self, owner):
        ResourceGroupMembership.objects.get_or_create(
            resource_group=self,
            user=owner,
            defaults={
                "role": "admin",
            },
        )

    def members(self):
        member_set = set()
        for membership in ResourceGroupMembership.objects.filter(
                resource_group=self):
            member = membership.user
            member.role = membership.role
            member_set.add(member)
        return member_set
Ejemplo n.º 12
0
 def validate_foreign_key_field(value):
     if not isinstance(value,
                       int) and not _lazy_re_compile('^\d+$').match(value):
         raise ValidationError(
             'ForeignKeyField字段数据, 必须为int类型或正整数字符串. 当前值为: {0}'.format(
                 value))
     new_value = int(value)
     return new_value
Ejemplo n.º 13
0
class UserValidator:
	message = _('Невірно введені дані користувача.')
	code = 'invalid'
	names_regex = _lazy_re_compile(r'[A-z]{3,24}\Z', re.IGNORECASE)
	password_regex = _lazy_re_compile(r"([-!#$%&'.*+/=?^_`{}|~0-9A-Z]+){6,32}", re.IGNORECASE)
	password_alf_regex = _lazy_re_compile(r"[A-z]+", re.IGNORECASE)
	password_num_regex = _lazy_re_compile(r"[0-9]+", re.IGNORECASE)
	def __init__(self, message=None, code=None):
		if message is not None:
			self.message = message
		if code is not None:
			self.code = code

	def __call__(self, name, surname, email, pass1, pass2):
		self.ValidNames(name,surname)
		self.ValidEmail(email)
		self.ValidPasswords(pass1, pass2)

	def ValidNames(self, name, surname):
		if not self.names_regex.fullmatch(name) or not self.names_regex.match(surname):
			raise ValidationError(_('Ім\'я та фамілія повинні містити тільки літери ( 3-24літ. )'), code='names')

	def ValidEmail(self, emaila):
		validate_email = EmailValidator('Невірно введена E-mail адреса.')
		validate_email(emaila)
		try:
			User.objects.get(email=emaila)
			raise ValidationError(_('E-mail адреса зайнята.'), code='resemail')
		except User.DoesNotExist:
			pass
	def ValidPasswords(self, password, cpassword):
		if password != cpassword:
			raise ValidationError(_('Паролі повинні співпадати.'), code='notequals')
		if not self.password_regex.fullmatch(password):
			raise ValidationError(_('Недоступний пароль ( 6-32сим. )'), code='badpass')
		if not self.password_num_regex.search(password):
			raise ValidationError(_('Пароль повинен містити цифри.'), code='numpassword')
		if not self.password_alf_regex.search(password):
			raise ValidationError(_('Пароль повинен містити літери.'), code='alfpassword')

	def __eq__(self, other):
		return (
			isinstance(other, UserValidator) and
			(self.message == other.message) and
			(self.code == other.code)
		)
Ejemplo n.º 14
0
def validate_skype(value):
    value = force_text(value)
    skype_regex = _lazy_re_compile(r'[a-zA-Z][\w,.-]+$')

    if skype_regex.match(value):
        return True

    raise ValidationError(_("Invalid Skype username"))
Ejemplo n.º 15
0
def validate_telegram(value):
    value = force_text(value)
    telegram_regex = _lazy_re_compile(r'@[a-zA-Z]\w+[a-zA-Z0-9]$')

    if telegram_regex.match(value):
        return True

    raise ValidationError(_("Invalid Telegram username"))
Ejemplo n.º 16
0
class VariableSchemeUrlValidator(URLValidator):
    """ Валидатор URL который не проверяет схему URL """

    regex = _lazy_re_compile(
        r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
        r'(?:' + URLValidator.ipv4_re + '|' + URLValidator.ipv6_re + '|' +
        URLValidator.host_re + ')'
        r'(?::\d{2,5})?'  # port
        r'(?:[/?#][^\s]*)?'  # resource path
        r'\Z',
        re.IGNORECASE)

    def __call__(self, value):
        if '://' in value:
            scheme = value.split('://')[0].lower()
        else:
            scheme = None

        # отключаю проверку схемы url
        if scheme:
            if scheme not in self.schemes:
                raise ValidationError(self.message, code=self.code)

        try:
            super(URLValidator, self).__call__(value)
        except ValidationError as e:
            if value:
                try:
                    scheme, netloc, path, query, fragment = urlsplit(value)
                except ValueError:  # for example, "Invalid IPv6 URL"
                    raise ValidationError(self.message, code=self.code)
                try:
                    netloc = netloc.encode('idna').decode(
                        'ascii')  # IDN -> ACE
                except UnicodeError:  # invalid domain part
                    raise e
                url = urlunsplit((scheme, netloc, path, query, fragment))
                super().__call__(url)
            else:
                raise
        else:
            # Now verify IPv6 in the netloc part
            host_match = re.search(r'^\[(.+)\](?::\d{2,5})?$',
                                   urlsplit(value).netloc)
            if host_match:
                potential_ip = host_match.groups()[0]
                try:
                    validate_ipv6_address(potential_ip)
                except ValidationError:
                    raise ValidationError(self.message, code=self.code)

        # The maximum length of a full host name is 253 characters per RFC 1034
        # section 3.1. It's defined to be 255 bytes or less, but this includes
        # one byte for the length of the name and one byte for the trailing dot
        # that's used to indicate absolute names in DNS.
        if len(urlsplit(value).netloc) > 253:
            raise ValidationError(self.message, code=self.code)
Ejemplo n.º 17
0
class UserProfileForm(forms.ModelForm):

    validate_username = RegexValidator(
        _lazy_re_compile(r'^[-a-z0-9_]+\Z'),
        "Your username cannot include spaces, punctuation or capital letters.",
        'invalid')

    first_name = forms.CharField(label='First name')
    last_name = forms.CharField(label='Last name')
    username = forms.CharField(label='Username',
                               validators=[validate_username])
    country = forms.ModelChoiceField(required=True,
                                     queryset=Country.objects,
                                     label='Country',
                                     empty_label=None)

    class Meta:
        model = UserProfile
        fields = (
            # personal info (also includes first_name and last_name)
            'profile_photo',
            'bio',
            # work
            'organisations',
            'skills',
            'qualifications',
            'specialisations',
            'areas_of_law',
            # social
            'twitter_username',
            'linkedin_profile',
        )

    def clean_twitter_username(self):
        if self.cleaned_data['twitter_username']:
            twitter_username = self.cleaned_data['twitter_username'].strip('@')
            return twitter_username

    def clean_username(self):
        username = self.cleaned_data['username']
        if User.objects.filter(username=username).exclude(
                pk=self.instance.user.pk).exists():
            raise forms.ValidationError("This username is already taken.")
        return username

    def save(self, commit=True):
        super(UserProfileForm, self).save()
        self.instance.user.first_name = self.cleaned_data['first_name']
        self.instance.user.last_name = self.cleaned_data['last_name']
        self.instance.user.username = self.cleaned_data['username']
        self.instance.user.editor.country = self.cleaned_data['country']
        self.instance.user.editor.save()
        self.instance.user.save()
Ejemplo n.º 18
0
    def test_create_with_validation_rule(self):
        ValidationRule.objects.create(
            field_reference=(EducationGroupYear._meta.db_table + ".acronym." +
                             self.education_group_type.external_id),
            initial_value="yolo",
            status_field=NOT_REQUIRED,
            regex_rule="([A-Z]{2})(.*)")

        form = GroupYearModelForm(
            education_group_type=self.education_group_type, user=self.user)

        self.assertEqual(form.fields["acronym"].initial, "yolo")
        self.assertEqual(form.fields["acronym"].required, False)
        self.assertEqual(form.fields["acronym"].validators[1].regex,
                         _lazy_re_compile("([A-Z]{2})(.*)"))
Ejemplo n.º 19
0
 def validate_many_to_many_field(value):
     assert isinstance(
         value, (tuple, list)
     ), 'ManyToManyField字段数据, 必须为(list, tuple). 当前值为: {0}'.format(value)
     new_value = list()
     for fv in value:
         if not isinstance(
                 value,
             (int, Model)) and not _lazy_re_compile('^\d+$').match(fv):
             raise ValidationError(
                 'ManyToManyField字段数据序列的值, 只能为(int, Model, 正整数字符串)类型. 当前值为: {0}'
                 .format(value))
         new_value.append(int(fv))
     new_value.sort()
     return new_value
Ejemplo n.º 20
0
class Service(models.Model):

    site = models.ForeignKey(Site, related_name="services")
    name = models.CharField(
        max_length=50,
        validators=[
            validators.RegexValidator(
                validators._lazy_re_compile(r"^[a-zA-Z0-9-]+$"),
                "Invalid name. (hint: ^[a-zA-Z0-9-]+$)",
            ),
        ])
    created = models.DateTimeField(default=timezone.now)

    class Meta:
        unique_together = [("site", "name")]
Ejemplo n.º 21
0
class ResourceGroup(models.Model):

    name = models.CharField(
        max_length=100,
        unique=True,
        validators=[
            validators.RegexValidator(
                validators._lazy_re_compile(r"^[a-zA-Z0-9_-]+$"),
                "Invaid name. (hint: ^[a-zA-Z0-9_-]+$)",
            ),
        ]
    )
    personal = models.BooleanField(default=False)

    created = models.DateTimeField(default=timezone.now)
    deleted = models.DateTimeField(null=True, blank=True)

    objects = ResourceGroupManager()

    def __str__(self):
        return self.name

    def delete(self, **kwargs):
        for site in self.site_set.active():
            site.delete()
        self.deleted = timezone.now()
        self.save()

    def set_owner(self, owner):
        ResourceGroupUser.objects.get_or_create(
            resource_group=self,
            user=owner,
            defaults={
                "role": "admin",
            },
        )

    def users(self):
        us = []
        for membership in ResourceGroupUser.objects.filter(resource_group=self, resource_group__deleted__isnull=True):
            user = membership.user
            user.role = membership.role
            us.append(user)
        return us
Ejemplo n.º 22
0
class EnhancedURLValidator(URLValidator):
    """
    Extends Django's built-in URLValidator to permit the use of hostnames with no domain extension and enforce allowed
    schemes specified in the configuration.
    """
    fqdn_re = URLValidator.hostname_re + URLValidator.domain_re + URLValidator.tld_re
    host_res = [
        URLValidator.ipv4_re, URLValidator.ipv6_re, fqdn_re,
        URLValidator.hostname_re
    ]
    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # Scheme (enforced separately)
        r'(?:\S+(?::\S*)?@)?'  # HTTP basic authentication
        r'(?:' + '|'.join(host_res) + ')'  # IPv4, IPv6, FQDN, or hostname
        r'(?::\d{2,5})?'  # Port number
        r'(?:[/?#][^\s]*)?'  # Path
        r'\Z',
        re.IGNORECASE)
    schemes = settings.ALLOWED_URL_SCHEMES
Ejemplo n.º 23
0
 def __init__(self, **kwargs):
     self.allow_blank = kwargs.pop('allow_blank', False)
     self.trim_whitespace = False
     self.max_length = 24
     self.min_length = 24
     super(serializers.CharField, self).__init__(**kwargs)
     message = self.error_messages['max_length'].format(
         max_length=self.max_length)
     self.validators.append(
         MaxLengthValidator(self.max_length, message=message))
     message = self.error_messages['min_length'].format(
         min_length=self.min_length)
     self.validators.append(
         MinLengthValidator(self.min_length, message=message))
     self.validators.append(
         RegexValidator(
             _lazy_re_compile('^[\da-f]+$'),
             message=_('Enter a valid id.'),
             code='invalid',
         ))
Ejemplo n.º 24
0
class HostnameURLValidator(URLValidator):
    """
    Custom URL Validator that support the presence of only the hostname (e.g.: "https://hostname/" is a valid value)
    """
    tld_re = (
            r'(\.'  # dot
            r'(?!-)'  # can't start with a dash
            r'(?:[a-z' + URLValidator.ul + '-]{2,63}'  # domain label
                                           r'|xn--[a-z0-9]{1,59})'  # or punycode label
                                           r'(?<!-)'  # can't end with a dash
                                           r'\.?)*'  # may have a trailing dot
    )
    host_re = '(' + URLValidator.hostname_re + URLValidator.domain_re + tld_re + '|localhost)'

    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
        r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
        r'(?:' + URLValidator.ipv4_re + '|' + URLValidator.ipv6_re + '|' + host_re + ')'
                                                                                     r'(?::\d{2,5})?'  # port
                                                                                     r'(?:[/?#][^\s]*)?'  # resource path
                                                                                     r'\Z', re.IGNORECASE)
Ejemplo n.º 25
0
class URLValidator(DjangoURLValidator):
    """
    Set validation regex rules for URLs.
    """

    ul = "\u00a1-\uffff"  # unicode letters range (must not be a raw string)

    # IP patterns
    ipv4_re = (
        r"(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}"
    )
    ipv6_re = r"\[[0-9a-f:\.]+\]"  # (simple regex, validated later)

    # Host patterns
    hostname_re = (r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" +
                   ul + r"0-9])?")
    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
    domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*"
    tld_re = (
        r"\."  # dot
        r"(?!-)"  # can't start with a dash
        r"(?:[a-z" + ul + "-]{2,63}"  # domain label
        r"|xn--[a-z0-9]{1,59})"  # or punycode label
        r"(?<!-)"  # can't end with a dash
        r"\.?"  # may have a trailing dot
    )
    host_re = "(" + hostname_re + domain_re + tld_re + "|localhost|testserver)"

    regex = _lazy_re_compile(
        r"^(?:[a-z0-9\.\-\+]*)://"  # scheme is validated separately
        r"(?:\S+(?::\S*)?@)?"  # user:pass authentication
        r"(?:" + ipv4_re + "|" + ipv6_re + "|" + host_re + ")"
        r"(?::\d{2,5})?"  # port
        r"(?:[/?#][^\s]*)?"  # resource path
        r"\Z",
        re.IGNORECASE,
    )
    message = _("Enter a valid URL.")
    schemes = ["http", "https", "ftp", "ftps"]
Ejemplo n.º 26
0
class UsernameField(forms.CharField):

    validate_ckan = validators.RegexValidator(
        validators._lazy_re_compile(r'^[-a-z0-9_]+\Z'), 'pas ok', 'invalid')

    def __init__(self, *args, **kwargs):
        kwargs.setdefault(
            'error_messages', {
                'invalid':
                'Seuls les caractères alpha-numériques en minuscule et les caractères - et _ sont autorisés.'
            })
        kwargs.setdefault('label', "Nom d'utilisateur*")
        kwargs.setdefault('max_length', 100)
        kwargs.setdefault('min_length', 3)
        kwargs.setdefault('required', True)
        kwargs.setdefault('validators', [self.validate_ckan])
        # TODO Le validateur ne voit pas les MAJ (à corriger..)
        kwargs.setdefault(
            'widget',
            forms.TextInput(attrs={'placeholder': "Nom d'utilisateur"}))

        super().__init__(*args, **kwargs)
Ejemplo n.º 27
0
    def __init__(self,
                 regex=None,
                 message=None,
                 code=None,
                 inverse_match=None,
                 flags=None):
        if regex is not None:
            self.regex = regex
        if message is not None:
            self.message = message
        if code is not None:
            self.code = code
        if inverse_match is not None:
            self.inverse_match = inverse_match
        if flags is not None:
            self.flags = flags
        if self.flags and not isinstance(self.regex, str):
            raise TypeError(
                "If the flags are set, regex must be a regular expression string."
            )

        self.regex = _lazy_re_compile(self.regex, self.flags)
Ejemplo n.º 28
0
class TmsUrlField(models.CharField):

    ul = '\u00a1-\uffff'  # unicode letters range (must not be a raw string)

    # IP patterns
    ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
    ipv6_re = r'\[[0-9a-f:\.]+\]'  # (simple regex, validated later)

    # Host patterns
    hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
    subdomain_switch_re = r'(\{switch:((?:\w+)(?:,\w+)*)\})'
    hostname_with_switch_re = '(' + hostname_re + '|' + subdomain_switch_re + ')'

    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
    domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
    tld_re = (
        r'\.'  # dot
        r'(?!-)'  # can't start with a dash
        r'(?:[a-z' + ul + '-]{2,63}'  # domain label
        r'|xn--[a-z0-9]{1,59})'  # or punycode label
        r'(?<!-)'  # can't end with a dash
        r'\.?'  # may have a trailing dot
    )
    host_re = '(' + hostname_with_switch_re + domain_re + tld_re + '|localhost)'

    regex = validators._lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
        r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
        r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')'
        r'(?::\d{2,5})?'  # port
        r'(?:[/?#][^\s]*)?'  # resource path
        r'\Z',
        re.IGNORECASE)

    default_validators = [
        validators.URLValidator(schemes=['http', 'https'],
                                regex=regex,
                                message=_('Enter a valid TMS URL.'))
    ]
Ejemplo n.º 29
0
class LDAPServerURIField(fields.URLField):

    tld_re = (
        r'\.'  # dot
        r'(?!-)'  # can't start with a dash
        r'(?:[a-z' + URLValidator.ul + r'0-9' +
        '-]{2,63}'  # domain label, this line was changed from the original URLValidator
        r'|xn--[a-z0-9]{1,59})'  # or punycode label
        r'(?<!-)'  # can't end with a dash
        r'\.?'  # may have a trailing dot
    )

    host_re = '(' + URLValidator.hostname_re + URLValidator.domain_re + tld_re + '|localhost)'

    regex = _lazy_re_compile(
        r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
        r'(?:[^\s:@/]+(?::[^\s:@/]*)?@)?'  # user:pass authentication
        r'(?:' + URLValidator.ipv4_re + '|' + URLValidator.ipv6_re + '|' +
        host_re + ')'
        r'(?::\d{2,5})?'  # port
        r'(?:[/?#][^\s]*)?'  # resource path
        r'\Z',
        re.IGNORECASE)

    def __init__(self, **kwargs):

        kwargs.setdefault('schemes', ('ldap', 'ldaps'))
        kwargs.setdefault('allow_plain_hostname', True)
        kwargs.setdefault('regex', LDAPServerURIField.regex)
        super(LDAPServerURIField, self).__init__(**kwargs)

    def run_validators(self, value):

        for url in filter(None, re.split(r'[, ]', (value or ''))):
            super(LDAPServerURIField, self).run_validators(url)
        return value
Ejemplo n.º 30
0
class IbanValidator(object):
    IBAN_REGEX = _lazy_re_compile(r'^[A-Z0-9]{0,34}$')
    LETTER_MAP = tuple(zip(string.ascii_uppercase, range(10, 36)))
    message = _('IBAN is not valid')

    def __init__(self, message=None):
        if message is not None:
            self.message = message
        self.letter_map = dict(self.LETTER_MAP)

    def __call__(self, value):
        if not value or not self.IBAN_REGEX.match(value):
            raise ValidationError(self.message)

        iban = self._move_first_4_chars_to_the_end(value)
        number = self._get_iban_number(iban)

        if not self._is_mod_97_valid(number):
            raise ValidationError(self.message)

    def _get_iban_number(self, value):
        return int(self._get_iban_number_as_str(value))

    def _get_iban_number_as_str(self, value):
        return ''.join([self._get_translated_number_as_str(s) for s in value])

    def _get_translated_number_as_str(self, symbol):
        return str(self.letter_map.get(symbol, symbol))

    @staticmethod
    def _move_first_4_chars_to_the_end(value):
        return value[4:] + value[:4]

    @staticmethod
    def _is_mod_97_valid(number):
        return number % 97 == 1
Ejemplo n.º 31
0
from django.core.validators import RegexValidator, _lazy_re_compile
from django.utils.translation import ugettext_lazy as _

key_validator = RegexValidator(
    _lazy_re_compile("^[^\s/\.]+$"), message=_("Key must not contain spaces, dots or slashes."), code="invalid"
)

mac_address_validator = RegexValidator(
    _lazy_re_compile("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})"),
    message=_("Must be a valid mac address."),
    code="invalid",
)
Ejemplo n.º 32
0
 def __init__(self, schemes=None, **kwargs):
     self.schemes = schemes or ('http', 'https', 'ftp', 'sftp')
     self.scheme_list = '|'.join(self.schemes)
     self.regex = _lazy_re_compile(self.netloc_re)
Ejemplo n.º 33
0
from deployutils.crypt import decrypt, encrypt

from . import settings
from .utils import get_site_model


SUBDOMAIN_RE = r'^[-a-zA-Z0-9_]+\Z'
SUBDOMAIN_SLUG = RegexValidator(
    SUBDOMAIN_RE,
    _("Enter a valid subdomain consisting of letters, digits or hyphens."),
    'invalid'
)
HOST_VALIDATOR = RegexValidator(
    _lazy_re_compile(
        r'(?:' + URLValidator.ipv4_re + '|' + URLValidator.ipv6_re + \
        '|' + URLValidator.host_re + ')' # host
        r'(?::\d{2,5})?'                                       # port
        r'(?:[/?#][^\s]*)?'                                    # resource path
        r'\Z', re.IGNORECASE),
    _("Enter a valid host, optionally followed by a port and resource path."),
    'invalid'
)

def domain_name_validator(value):
    """
    Validates that the given value contains no whitespaces to prevent common
    typos.
    """
    if not value:
        return
    checks = ((s in value) for s in string.whitespace)
    if any(checks):
Ejemplo n.º 34
0
from django.core.validators import RegexValidator, _lazy_re_compile
from django.utils.translation import ugettext_lazy as _

key_validator = RegexValidator(
    _lazy_re_compile('^[^\s/\.]+$'),
    message=_('Key must not contain spaces, dots or slashes.'),
    code='invalid',
)
Ejemplo n.º 35
0
from django.forms import CharField
from django.forms.widgets import TextInput
from django.core.validators import RegexValidator, _lazy_re_compile
from django.forms.fields import EMPTY_VALUES
from django.forms.utils import ValidationError
from django.utils.translation import gettext_lazy as _
from netaddr import EUI, AddrFormatError
from . import MAC_ADDR_REGEX

mac_address_validator = RegexValidator(
    _lazy_re_compile(MAC_ADDR_REGEX),
    message=_('Enter a valid integer.'),
    code='invalid',
)


class MACAddressField(CharField):
    widget = TextInput
    default_validators = [mac_address_validator]
    default_error_messages = {
        'invalid': _('Enter a valid MAC Address.'),
    }

    def clean(self, value):
        """
        Validates that EUI() can be called on the input. Returns the result
        of EUI(). Returns None for empty values.
        """
        value = super(MACAddressField, self).clean(value)
        if value in EMPTY_VALUES:
            return None
Ejemplo n.º 36
0
from django.core.exceptions import ValidationError, PermissionDenied
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator, _lazy_re_compile
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone

from osf.models.admin_log_entry import (
    update_admin_log,
    EMBARGO_UPDATED
)

from website import settings

validate_slug = RegexValidator(
    _lazy_re_compile(r'^[a-z]+\Z'),
    _("Enter a valid 'slug' consisting only of lowercase letters."),
    'invalid'
)

def reverse_qs(view, urlconf=None, args=None, kwargs=None, current_app=None, query_kwargs=None):
    base_url = reverse(view, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app)
    if query_kwargs:
        return '{}?{}'.format(base_url, urlencode(query_kwargs))


def osf_staff_check(user):
    return user.is_authenticated and user.is_staff


def get_subject_rules(subjects_selected):
Ejemplo n.º 37
0
from django.core.validators import RegexValidator, _lazy_re_compile
from django.utils.translation import ugettext_lazy as _


key_validator = RegexValidator(
    _lazy_re_compile("^[^\s/\.]+$"), message=_("Key must not contain spaces, dots or slashes."), code="invalid"
)