captcha.py 1.3 KB

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