Coverage for benefits/core/recaptcha.py: 53%
13 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-19 00:56 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-19 00:56 +0000
1"""
2The core application: helpers to work with reCAPTCHA.
3"""
5import requests
7from django.conf import settings
10DATA_FIELD = "g-recaptcha-response"
13def has_error(form) -> bool:
14 """True if the given form has a reCAPTCHA error. False otherwise."""
15 return any([s for (_, v) in form.errors.items() for s in v if "reCAPTCHA" in s])
18def verify(form_data: dict) -> bool:
19 """
20 Check with Google reCAPTCHA if the given response is a valid user.
21 See https://developers.google.com/recaptcha/docs/verify
22 """
23 if not settings.RECAPTCHA_ENABLED: 23 ↛ 26line 23 didn't jump to line 26 because the condition on line 23 was always true
24 return True
26 if not form_data or DATA_FIELD not in form_data:
27 return False
29 payload = dict(secret=settings.RECAPTCHA_SECRET_KEY, response=form_data[DATA_FIELD])
30 response = requests.post(settings.RECAPTCHA_VERIFY_URL, payload, timeout=settings.REQUESTS_TIMEOUT).json()
32 return bool(response["success"])