captcha.py 1.3 KB

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