captcha.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import requests
  2. from django.core.exceptions import ValidationError
  3. from django.utils.translation import ugettext as _
  4. from misago.conf import settings
  5. def recaptcha_test(request):
  6. r = requests.post('https://www.google.com/recaptcha/api/siteverify', data={
  7. 'secret': settings.recaptcha_secret_key,
  8. 'response': request.data.get('captcha'),
  9. 'remoteip': request.user_ip
  10. })
  11. if r.status_code == 200:
  12. response_json = r.json()
  13. if not response_json.get('success'):
  14. raise ValidationError(_("Please try again."))
  15. else:
  16. raise ValidationError(_("Failed to contact reCAPTCHA API."))
  17. def qacaptcha_test(request):
  18. answer = request.data.get('captcha', '').lower()
  19. for predefined_answer in settings.qa_answers.lower().splitlines():
  20. predefined_answer = predefined_answer.strip().lower()
  21. if answer == predefined_answer:
  22. break
  23. else:
  24. raise ValidationError(_("Entered answer is incorrect."))
  25. def nocaptcha_test(request):
  26. return # no captcha means no validation
  27. CAPTCHA_TESTS = {
  28. 're': recaptcha_test,
  29. 'qa': qacaptcha_test,
  30. 'no': nocaptcha_test,
  31. }
  32. def test_request(request):
  33. CAPTCHA_TESTS[settings.captcha_type](request)