validators.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import json
  2. import re
  3. import requests
  4. from django.contrib.auth import get_user_model
  5. from django.core.exceptions import ValidationError
  6. from django.core.validators import validate_email as validate_email_content
  7. from django.utils.encoding import force_str
  8. from django.utils.module_loading import import_string
  9. from django.utils.translation import ugettext_lazy as _
  10. from django.utils.translation import ungettext
  11. from misago.conf import settings
  12. from .bans import get_email_ban, get_username_ban
  13. USERNAME_RE = re.compile(r'^[0-9a-z]+$', re.IGNORECASE)
  14. UserModel = get_user_model()
  15. # E-mail validators
  16. def validate_email_available(value, exclude=None):
  17. try:
  18. user = UserModel.objects.get_by_email(value)
  19. if not exclude or user.pk != exclude.pk:
  20. raise ValidationError(_("This e-mail address is not available."))
  21. except UserModel.DoesNotExist:
  22. pass
  23. def validate_email_banned(value):
  24. ban = get_email_ban(value, registration_only=True)
  25. if ban:
  26. if ban.user_message:
  27. raise ValidationError(ban.user_message)
  28. else:
  29. raise ValidationError(_("This e-mail address is not allowed."))
  30. def validate_email(value, exclude=None):
  31. """shortcut function that does complete validation of email"""
  32. validate_email_content(value)
  33. validate_email_available(value, exclude)
  34. validate_email_banned(value)
  35. # Username validators
  36. def validate_username_available(value, exclude=None):
  37. try:
  38. user = UserModel.objects.get_by_username(value)
  39. if not exclude or user.pk != exclude.pk:
  40. raise ValidationError(_("This username is not available."))
  41. except UserModel.DoesNotExist:
  42. pass
  43. def validate_username_banned(value):
  44. ban = get_username_ban(value, registration_only=True)
  45. if ban:
  46. if ban.user_message:
  47. raise ValidationError(ban.user_message)
  48. else:
  49. raise ValidationError(_("This username is not allowed."))
  50. def validate_username_content(value):
  51. if not USERNAME_RE.match(value):
  52. raise ValidationError(_("Username can only contain latin alphabet letters and digits."))
  53. def validate_username_length(value):
  54. if len(value) < settings.username_length_min:
  55. message = ungettext(
  56. "Username must be at least %(limit_value)s character long.",
  57. "Username must be at least %(limit_value)s characters long.",
  58. settings.username_length_min
  59. )
  60. raise ValidationError(message % {'limit_value': settings.username_length_min})
  61. if len(value) > settings.username_length_max:
  62. message = ungettext(
  63. "Username cannot be longer than %(limit_value)s characters.",
  64. "Username cannot be longer than %(limit_value)s characters.",
  65. settings.username_length_max
  66. )
  67. raise ValidationError(message % {'limit_value': settings.username_length_max})
  68. def validate_username(value, exclude=None):
  69. """shortcut function that does complete validation of username"""
  70. validate_username_length(value)
  71. validate_username_content(value)
  72. validate_username_available(value, exclude)
  73. validate_username_banned(value)
  74. # New account validators
  75. SFS_API_URL = 'http://api.stopforumspam.org/api?email=%(email)s&ip=%(ip)s&f=json&confidence' # noqa
  76. def validate_with_sfs(request, cleaned_data, add_error):
  77. if settings.MISAGO_USE_STOP_FORUM_SPAM and cleaned_data.get('email'):
  78. _real_validate_with_sfs(request.user_ip, cleaned_data['email'])
  79. def _real_validate_with_sfs(ip, email):
  80. try:
  81. r = requests.get(SFS_API_URL % {'email': email, 'ip': ip}, timeout=5)
  82. r.raise_for_status()
  83. api_response = json.loads(force_str(r.content))
  84. ip_score = api_response.get('ip', {}).get('confidence', 0)
  85. email_score = api_response.get('email', {}).get('confidence', 0)
  86. api_score = max((ip_score, email_score))
  87. if api_score > settings.MISAGO_STOP_FORUM_SPAM_MIN_CONFIDENCE:
  88. raise ValidationError(_("Data entered was found in spammers database."))
  89. except requests.exceptions.RequestException:
  90. pass # todo: log those somewhere
  91. def validate_gmail_email(request, cleaned_data, add_error):
  92. email = cleaned_data.get('email', '')
  93. if '@' not in email:
  94. return
  95. username, domain = email.lower().split('@')
  96. if domain == 'gmail.com' and username.count('.') > 5:
  97. add_error('email', ValidationError(_("This email is not allowed.")))
  98. # Registration validation
  99. validators_list = settings.MISAGO_NEW_REGISTRATIONS_VALIDATORS
  100. REGISTRATION_VALIDATORS = list(map(import_string, validators_list))
  101. def raise_validation_error(fieldname, validation_error):
  102. raise ValidationError()
  103. def validate_new_registration(request, cleaned_data, add_error=None, validators=None):
  104. validators = validators or REGISTRATION_VALIDATORS
  105. add_error = add_error or raise_validation_error
  106. for validator in validators:
  107. validator(request, cleaned_data, add_error)