validators.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import re
  2. from django.conf import settings
  3. from django.core.exceptions import ValidationError
  4. from django.utils.translation import ungettext, ugettext_lazy as _
  5. from misago.banning.models import check_ban
  6. from misago.settings.settings import Settings as DBSettings
  7. def validate_username(value, db_settings):
  8. value = unicode(value).strip()
  9. if len(value) < db_settings['username_length_min']:
  10. raise ValidationError(ungettext(
  11. 'Username must be at least one character long.',
  12. 'Username must be at least %(count)d characters long.',
  13. db_settings['username_length_min']
  14. ) % {
  15. 'count': db_settings['username_length_min'],
  16. })
  17. if len(value) > db_settings['username_length_max']:
  18. raise ValidationError(ungettext(
  19. 'Username cannot be longer than one characters.',
  20. 'Username cannot be longer than %(count)d characters.',
  21. db_settings['username_length_max']
  22. ) % {
  23. 'count': db_settings['username_length_max'],
  24. })
  25. if settings.UNICODE_USERNAMES:
  26. if not re.search('^[^\W_]+$', value, re.UNICODE):
  27. raise ValidationError(_("Username can only contain letters and digits."))
  28. else:
  29. if not re.search('^[^\W_]+$', value):
  30. raise ValidationError(_("Username can only contain latin alphabet letters and digits."))
  31. if check_ban(username=value):
  32. raise ValidationError(_("This username is forbidden."))
  33. def validate_password(value, db_settings):
  34. value = unicode(value).strip()
  35. if len(value) < db_settings['password_length']:
  36. raise ValidationError(ungettext(
  37. 'Correct password has to be at least one character long.',
  38. 'Correct password has to be at least %(count)d characters long.',
  39. db_settings['password_length']
  40. ) % {
  41. 'count': db_settings['password_length'],
  42. })
  43. for test in db_settings['password_complexity']:
  44. if test in ('case', 'digits', 'special'):
  45. if not re.search('[a-zA-Z]', value):
  46. raise ValidationError(_("Password must contain alphabetical characters."))
  47. if test == 'case':
  48. if not (re.search('[a-z]', value) and re.search('[A-Z]', value)):
  49. raise ValidationError(_("Password must contain characters that have different case."))
  50. if test == 'digits':
  51. if not re.search('[0-9]', value):
  52. raise ValidationError(_("Password must contain digits in addition to characters."))
  53. if test == 'special':
  54. if not re.search('[^0-9a-zA-Z]', value):
  55. raise ValidationError(_("Password must contain special (non alphanumerical) characters."))
  56. def validate_email(value):
  57. value = unicode(value).strip()
  58. if check_ban(email=value):
  59. raise ValidationError(_("This board forbids registrations using this e-mail address."))