Coverage for benefits/core/recaptcha.py: 53%

13 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-10-21 19:31 +0000

1""" 

2The core application: helpers to work with reCAPTCHA. 

3""" 

4 

5import requests 

6 

7from django.conf import settings 

8 

9 

10DATA_FIELD = "g-recaptcha-response" 

11 

12 

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]) 

16 

17 

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 

25 

26 if not form_data or DATA_FIELD not in form_data: 

27 return False 

28 

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() 

31 

32 return bool(response["success"])