Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validators.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import ipaddress
  2. import re
  3. from pathlib import Path
  4. from urllib.parse import urlsplit, urlunsplit
  5. from django.core.exceptions import ValidationError
  6. from django.utils.deconstruct import deconstructible
  7. from django.utils.functional import SimpleLazyObject
  8. from django.utils.ipv6 import is_valid_ipv6_address
  9. from django.utils.translation import gettext_lazy as _, ngettext_lazy
  10. # These values, if given to validate(), will trigger the self.required check.
  11. EMPTY_VALUES = (None, '', [], (), {})
  12. def _lazy_re_compile(regex, flags=0):
  13. """Lazily compile a regex with flags."""
  14. def _compile():
  15. # Compile the regex if it was not passed pre-compiled.
  16. if isinstance(regex, str):
  17. return re.compile(regex, flags)
  18. else:
  19. assert not flags, "flags must be empty if regex is passed pre-compiled"
  20. return regex
  21. return SimpleLazyObject(_compile)
  22. @deconstructible
  23. class RegexValidator:
  24. regex = ''
  25. message = _('Enter a valid value.')
  26. code = 'invalid'
  27. inverse_match = False
  28. flags = 0
  29. def __init__(self, regex=None, message=None, code=None, inverse_match=None, flags=None):
  30. if regex is not None:
  31. self.regex = regex
  32. if message is not None:
  33. self.message = message
  34. if code is not None:
  35. self.code = code
  36. if inverse_match is not None:
  37. self.inverse_match = inverse_match
  38. if flags is not None:
  39. self.flags = flags
  40. if self.flags and not isinstance(self.regex, str):
  41. raise TypeError("If the flags are set, regex must be a regular expression string.")
  42. self.regex = _lazy_re_compile(self.regex, self.flags)
  43. def __call__(self, value):
  44. """
  45. Validate that the input contains (or does *not* contain, if
  46. inverse_match is True) a match for the regular expression.
  47. """
  48. regex_matches = self.regex.search(str(value))
  49. invalid_input = regex_matches if self.inverse_match else not regex_matches
  50. if invalid_input:
  51. raise ValidationError(self.message, code=self.code)
  52. def __eq__(self, other):
  53. return (
  54. isinstance(other, RegexValidator) and
  55. self.regex.pattern == other.regex.pattern and
  56. self.regex.flags == other.regex.flags and
  57. (self.message == other.message) and
  58. (self.code == other.code) and
  59. (self.inverse_match == other.inverse_match)
  60. )
  61. @deconstructible
  62. class URLValidator(RegexValidator):
  63. ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string)
  64. # IP patterns
  65. 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}'
  66. ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later)
  67. # Host patterns
  68. hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
  69. # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
  70. domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
  71. tld_re = (
  72. r'\.' # dot
  73. r'(?!-)' # can't start with a dash
  74. r'(?:[a-z' + ul + '-]{2,63}' # domain label
  75. r'|xn--[a-z0-9]{1,59})' # or punycode label
  76. r'(?<!-)' # can't end with a dash
  77. r'\.?' # may have a trailing dot
  78. )
  79. host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)'
  80. regex = _lazy_re_compile(
  81. r'^(?:[a-z0-9\.\-\+]*)://' # scheme is validated separately
  82. r'(?:\S+(?::\S*)?@)?' # user:pass authentication
  83. r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')'
  84. r'(?::\d{2,5})?' # port
  85. r'(?:[/?#][^\s]*)?' # resource path
  86. r'\Z', re.IGNORECASE)
  87. message = _('Enter a valid URL.')
  88. schemes = ['http', 'https', 'ftp', 'ftps']
  89. def __init__(self, schemes=None, **kwargs):
  90. super().__init__(**kwargs)
  91. if schemes is not None:
  92. self.schemes = schemes
  93. def __call__(self, value):
  94. # Check first if the scheme is valid
  95. scheme = value.split('://')[0].lower()
  96. if scheme not in self.schemes:
  97. raise ValidationError(self.message, code=self.code)
  98. # Then check full URL
  99. try:
  100. super().__call__(value)
  101. except ValidationError as e:
  102. # Trivial case failed. Try for possible IDN domain
  103. if value:
  104. try:
  105. scheme, netloc, path, query, fragment = urlsplit(value)
  106. except ValueError: # for example, "Invalid IPv6 URL"
  107. raise ValidationError(self.message, code=self.code)
  108. try:
  109. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  110. except UnicodeError: # invalid domain part
  111. raise e
  112. url = urlunsplit((scheme, netloc, path, query, fragment))
  113. super().__call__(url)
  114. else:
  115. raise
  116. else:
  117. # Now verify IPv6 in the netloc part
  118. host_match = re.search(r'^\[(.+)\](?::\d{2,5})?$', urlsplit(value).netloc)
  119. if host_match:
  120. potential_ip = host_match.groups()[0]
  121. try:
  122. validate_ipv6_address(potential_ip)
  123. except ValidationError:
  124. raise ValidationError(self.message, code=self.code)
  125. # The maximum length of a full host name is 253 characters per RFC 1034
  126. # section 3.1. It's defined to be 255 bytes or less, but this includes
  127. # one byte for the length of the name and one byte for the trailing dot
  128. # that's used to indicate absolute names in DNS.
  129. if len(urlsplit(value).netloc) > 253:
  130. raise ValidationError(self.message, code=self.code)
  131. integer_validator = RegexValidator(
  132. _lazy_re_compile(r'^-?\d+\Z'),
  133. message=_('Enter a valid integer.'),
  134. code='invalid',
  135. )
  136. def validate_integer(value):
  137. return integer_validator(value)
  138. @deconstructible
  139. class EmailValidator:
  140. message = _('Enter a valid email address.')
  141. code = 'invalid'
  142. user_regex = _lazy_re_compile(
  143. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom
  144. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string
  145. re.IGNORECASE)
  146. domain_regex = _lazy_re_compile(
  147. # max length for domain name labels is 63 characters per RFC 1034
  148. r'((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\Z',
  149. re.IGNORECASE)
  150. literal_regex = _lazy_re_compile(
  151. # literal form, ipv4 or ipv6 address (SMTP 4.1.3)
  152. r'\[([A-f0-9:\.]+)\]\Z',
  153. re.IGNORECASE)
  154. domain_whitelist = ['localhost']
  155. def __init__(self, message=None, code=None, whitelist=None):
  156. if message is not None:
  157. self.message = message
  158. if code is not None:
  159. self.code = code
  160. if whitelist is not None:
  161. self.domain_whitelist = whitelist
  162. def __call__(self, value):
  163. if not value or '@' not in value:
  164. raise ValidationError(self.message, code=self.code)
  165. user_part, domain_part = value.rsplit('@', 1)
  166. if not self.user_regex.match(user_part):
  167. raise ValidationError(self.message, code=self.code)
  168. if (domain_part not in self.domain_whitelist and
  169. not self.validate_domain_part(domain_part)):
  170. # Try for possible IDN domain-part
  171. try:
  172. domain_part = domain_part.encode('idna').decode('ascii')
  173. except UnicodeError:
  174. pass
  175. else:
  176. if self.validate_domain_part(domain_part):
  177. return
  178. raise ValidationError(self.message, code=self.code)
  179. def validate_domain_part(self, domain_part):
  180. if self.domain_regex.match(domain_part):
  181. return True
  182. literal_match = self.literal_regex.match(domain_part)
  183. if literal_match:
  184. ip_address = literal_match.group(1)
  185. try:
  186. validate_ipv46_address(ip_address)
  187. return True
  188. except ValidationError:
  189. pass
  190. return False
  191. def __eq__(self, other):
  192. return (
  193. isinstance(other, EmailValidator) and
  194. (self.domain_whitelist == other.domain_whitelist) and
  195. (self.message == other.message) and
  196. (self.code == other.code)
  197. )
  198. validate_email = EmailValidator()
  199. slug_re = _lazy_re_compile(r'^[-a-zA-Z0-9_]+\Z')
  200. validate_slug = RegexValidator(
  201. slug_re,
  202. # Translators: "letters" means latin letters: a-z and A-Z.
  203. _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."),
  204. 'invalid'
  205. )
  206. slug_unicode_re = _lazy_re_compile(r'^[-\w]+\Z')
  207. validate_unicode_slug = RegexValidator(
  208. slug_unicode_re,
  209. _("Enter a valid 'slug' consisting of Unicode letters, numbers, underscores, or hyphens."),
  210. 'invalid'
  211. )
  212. def validate_ipv4_address(value):
  213. try:
  214. ipaddress.IPv4Address(value)
  215. except ValueError:
  216. raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid')
  217. def validate_ipv6_address(value):
  218. if not is_valid_ipv6_address(value):
  219. raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
  220. def validate_ipv46_address(value):
  221. try:
  222. validate_ipv4_address(value)
  223. except ValidationError:
  224. try:
  225. validate_ipv6_address(value)
  226. except ValidationError:
  227. raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
  228. ip_address_validator_map = {
  229. 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
  230. 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
  231. 'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')),
  232. }
  233. def ip_address_validators(protocol, unpack_ipv4):
  234. """
  235. Depending on the given parameters, return the appropriate validators for
  236. the GenericIPAddressField.
  237. """
  238. if protocol != 'both' and unpack_ipv4:
  239. raise ValueError(
  240. "You can only use `unpack_ipv4` if `protocol` is set to 'both'")
  241. try:
  242. return ip_address_validator_map[protocol.lower()]
  243. except KeyError:
  244. raise ValueError("The protocol '%s' is unknown. Supported: %s"
  245. % (protocol, list(ip_address_validator_map)))
  246. def int_list_validator(sep=',', message=None, code='invalid', allow_negative=False):
  247. regexp = _lazy_re_compile(r'^%(neg)s\d+(?:%(sep)s%(neg)s\d+)*\Z' % {
  248. 'neg': '(-)?' if allow_negative else '',
  249. 'sep': re.escape(sep),
  250. })
  251. return RegexValidator(regexp, message=message, code=code)
  252. validate_comma_separated_integer_list = int_list_validator(
  253. message=_('Enter only digits separated by commas.'),
  254. )
  255. @deconstructible
  256. class BaseValidator:
  257. message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
  258. code = 'limit_value'
  259. def __init__(self, limit_value, message=None):
  260. self.limit_value = limit_value
  261. if message:
  262. self.message = message
  263. def __call__(self, value):
  264. cleaned = self.clean(value)
  265. params = {'limit_value': self.limit_value, 'show_value': cleaned, 'value': value}
  266. if self.compare(cleaned, self.limit_value):
  267. raise ValidationError(self.message, code=self.code, params=params)
  268. def __eq__(self, other):
  269. return (
  270. isinstance(other, self.__class__) and
  271. self.limit_value == other.limit_value and
  272. self.message == other.message and
  273. self.code == other.code
  274. )
  275. def compare(self, a, b):
  276. return a is not b
  277. def clean(self, x):
  278. return x
  279. @deconstructible
  280. class MaxValueValidator(BaseValidator):
  281. message = _('Ensure this value is less than or equal to %(limit_value)s.')
  282. code = 'max_value'
  283. def compare(self, a, b):
  284. return a > b
  285. @deconstructible
  286. class MinValueValidator(BaseValidator):
  287. message = _('Ensure this value is greater than or equal to %(limit_value)s.')
  288. code = 'min_value'
  289. def compare(self, a, b):
  290. return a < b
  291. @deconstructible
  292. class MinLengthValidator(BaseValidator):
  293. message = ngettext_lazy(
  294. 'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
  295. 'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
  296. 'limit_value')
  297. code = 'min_length'
  298. def compare(self, a, b):
  299. return a < b
  300. def clean(self, x):
  301. return len(x)
  302. @deconstructible
  303. class MaxLengthValidator(BaseValidator):
  304. message = ngettext_lazy(
  305. 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).',
  306. 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).',
  307. 'limit_value')
  308. code = 'max_length'
  309. def compare(self, a, b):
  310. return a > b
  311. def clean(self, x):
  312. return len(x)
  313. @deconstructible
  314. class DecimalValidator:
  315. """
  316. Validate that the input does not exceed the maximum number of digits
  317. expected, otherwise raise ValidationError.
  318. """
  319. messages = {
  320. 'invalid': _('Enter a number.'),
  321. 'max_digits': ngettext_lazy(
  322. 'Ensure that there are no more than %(max)s digit in total.',
  323. 'Ensure that there are no more than %(max)s digits in total.',
  324. 'max'
  325. ),
  326. 'max_decimal_places': ngettext_lazy(
  327. 'Ensure that there are no more than %(max)s decimal place.',
  328. 'Ensure that there are no more than %(max)s decimal places.',
  329. 'max'
  330. ),
  331. 'max_whole_digits': ngettext_lazy(
  332. 'Ensure that there are no more than %(max)s digit before the decimal point.',
  333. 'Ensure that there are no more than %(max)s digits before the decimal point.',
  334. 'max'
  335. ),
  336. }
  337. def __init__(self, max_digits, decimal_places):
  338. self.max_digits = max_digits
  339. self.decimal_places = decimal_places
  340. def __call__(self, value):
  341. digit_tuple, exponent = value.as_tuple()[1:]
  342. if exponent in {'F', 'n', 'N'}:
  343. raise ValidationError(self.messages['invalid'])
  344. if exponent >= 0:
  345. # A positive exponent adds that many trailing zeros.
  346. digits = len(digit_tuple) + exponent
  347. decimals = 0
  348. else:
  349. # If the absolute value of the negative exponent is larger than the
  350. # number of digits, then it's the same as the number of digits,
  351. # because it'll consume all of the digits in digit_tuple and then
  352. # add abs(exponent) - len(digit_tuple) leading zeros after the
  353. # decimal point.
  354. if abs(exponent) > len(digit_tuple):
  355. digits = decimals = abs(exponent)
  356. else:
  357. digits = len(digit_tuple)
  358. decimals = abs(exponent)
  359. whole_digits = digits - decimals
  360. if self.max_digits is not None and digits > self.max_digits:
  361. raise ValidationError(
  362. self.messages['max_digits'],
  363. code='max_digits',
  364. params={'max': self.max_digits},
  365. )
  366. if self.decimal_places is not None and decimals > self.decimal_places:
  367. raise ValidationError(
  368. self.messages['max_decimal_places'],
  369. code='max_decimal_places',
  370. params={'max': self.decimal_places},
  371. )
  372. if (self.max_digits is not None and self.decimal_places is not None and
  373. whole_digits > (self.max_digits - self.decimal_places)):
  374. raise ValidationError(
  375. self.messages['max_whole_digits'],
  376. code='max_whole_digits',
  377. params={'max': (self.max_digits - self.decimal_places)},
  378. )
  379. def __eq__(self, other):
  380. return (
  381. isinstance(other, self.__class__) and
  382. self.max_digits == other.max_digits and
  383. self.decimal_places == other.decimal_places
  384. )
  385. @deconstructible
  386. class FileExtensionValidator:
  387. message = _(
  388. "File extension '%(extension)s' is not allowed. "
  389. "Allowed extensions are: '%(allowed_extensions)s'."
  390. )
  391. code = 'invalid_extension'
  392. def __init__(self, allowed_extensions=None, message=None, code=None):
  393. if allowed_extensions is not None:
  394. allowed_extensions = [allowed_extension.lower() for allowed_extension in allowed_extensions]
  395. self.allowed_extensions = allowed_extensions
  396. if message is not None:
  397. self.message = message
  398. if code is not None:
  399. self.code = code
  400. def __call__(self, value):
  401. extension = Path(value.name).suffix[1:].lower()
  402. if self.allowed_extensions is not None and extension not in self.allowed_extensions:
  403. raise ValidationError(
  404. self.message,
  405. code=self.code,
  406. params={
  407. 'extension': extension,
  408. 'allowed_extensions': ', '.join(self.allowed_extensions)
  409. }
  410. )
  411. def __eq__(self, other):
  412. return (
  413. isinstance(other, self.__class__) and
  414. self.allowed_extensions == other.allowed_extensions and
  415. self.message == other.message and
  416. self.code == other.code
  417. )
  418. def get_available_image_extensions():
  419. try:
  420. from PIL import Image
  421. except ImportError:
  422. return []
  423. else:
  424. Image.init()
  425. return [ext.lower()[1:] for ext in Image.EXTENSION]
  426. def validate_image_file_extension(value):
  427. return FileExtensionValidator(allowed_extensions=get_available_image_extensions())(value)
  428. @deconstructible
  429. class ProhibitNullCharactersValidator:
  430. """Validate that the string doesn't contain the null character."""
  431. message = _('Null characters are not allowed.')
  432. code = 'null_characters_not_allowed'
  433. def __init__(self, message=None, code=None):
  434. if message is not None:
  435. self.message = message
  436. if code is not None:
  437. self.code = code
  438. def __call__(self, value):
  439. if '\x00' in str(value):
  440. raise ValidationError(self.message, code=self.code)
  441. def __eq__(self, other):
  442. return (
  443. isinstance(other, self.__class__) and
  444. self.message == other.message and
  445. self.code == other.code
  446. )