validators.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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):
  8. value = unicode(value).strip()
  9. if len(value) < 3:
  10. raise ValidationError(_("Username cannot be shorter than 3 characters."))
  11. if len(value) > 12:
  12. raise ValidationError(_("Username cannot be longer than 12 characters."))
  13. if settings.UNICODE_USERNAMES:
  14. if not re.search('^[^\W_]+$', value, re.UNICODE):
  15. raise ValidationError(_("Username can only contain letters and digits."))
  16. else:
  17. if not re.search('^[^\W_]+$', value):
  18. raise ValidationError(_("Username can only contain latin alphabet letters and digits."))
  19. if check_ban(username=value):
  20. raise ValidationError(_("This username is forbidden."))
  21. def validate_password(value):
  22. value = unicode(value).strip()
  23. db_settings = DBSettings()
  24. if len(value) < db_settings['password_length']:
  25. raise ValidationError(ungettext(
  26. 'Correct password has to be at least one character long.',
  27. 'Correct password has to be at least %(count)d characters long.',
  28. db_settings['password_length']
  29. ) % {
  30. 'count': db_settings['password_length'],
  31. })
  32. for test in db_settings['password_complexity']:
  33. if test in ('case', 'digits', 'special'):
  34. if not re.search('[a-zA-Z]', value):
  35. raise ValidationError(_("Password must contain alphabetical characters."))
  36. if test == 'case':
  37. if not (re.search('[a-z]', value) and re.search('[A-Z]', value)):
  38. raise ValidationError(_("Password must contain characters that have different case."))
  39. if test == 'digits':
  40. if not re.search('[0-9]', value):
  41. raise ValidationError(_("Password must contain digits in addition to characters."))
  42. if test == 'special':
  43. if not re.search('[^0-9a-zA-Z]', value):
  44. raise ValidationError(_("Password must contain special (non alphanumerical) characters."))
  45. def validate_email(value):
  46. value = unicode(value).strip()
  47. if check_ban(email=value):
  48. raise ValidationError(_("This board forbids registrations using this e-mail address."))