|
| 1 | +import requests |
| 2 | +import json |
| 3 | +from django.conf import settings |
| 4 | +from django.utils.translation import gettext as _ |
| 5 | + |
| 6 | + |
| 7 | +def verify_recaptcha_enterprise(token, action='submit'): |
| 8 | + if not all([settings.RECAPTCHA_PROJECT_ID, settings.RECAPTCHA_API_KEY, settings.RECAPTCHA_SITE_KEY]): |
| 9 | + return { |
| 10 | + 'success': False, |
| 11 | + 'error': 'reCAPTCHA configuration incomplete' |
| 12 | + } |
| 13 | + |
| 14 | + url = settings.RECAPTCHA_VERIFY_URL.format(project_id=settings.RECAPTCHA_PROJECT_ID, api_key=settings.RECAPTCHA_API_KEY) |
| 15 | + |
| 16 | + assessment_data = { |
| 17 | + "event": { |
| 18 | + "token": token, |
| 19 | + "siteKey": settings.RECAPTCHA_SITE_KEY, |
| 20 | + "expectedAction": action |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + headers = { |
| 25 | + 'Content-Type': 'application/json', |
| 26 | + } |
| 27 | + |
| 28 | + try: |
| 29 | + response = requests.post(url, json=assessment_data, headers=headers) |
| 30 | + response.raise_for_status() |
| 31 | + |
| 32 | + result = response.json() |
| 33 | + |
| 34 | + if 'tokenProperties' in result and 'valid' in result['tokenProperties']: |
| 35 | + is_valid = result['tokenProperties']['valid'] |
| 36 | + score = result.get('riskAnalysis', {}).get('score', 0.0) |
| 37 | + action_matched = result.get('tokenProperties', {}).get('action') == action |
| 38 | + |
| 39 | + return { |
| 40 | + 'success': is_valid and action_matched, |
| 41 | + 'score': score, |
| 42 | + 'action_matched': action_matched, |
| 43 | + 'raw_response': result |
| 44 | + } |
| 45 | + else: |
| 46 | + return { |
| 47 | + 'success': False, |
| 48 | + 'error': 'Invalid response format from reCAPTCHA Enterprise' |
| 49 | + } |
| 50 | + |
| 51 | + except requests.exceptions.RequestException as e: |
| 52 | + return { |
| 53 | + 'success': False, |
| 54 | + 'error': f'Request failed: {str(e)}' |
| 55 | + } |
| 56 | + except json.JSONDecodeError as e: |
| 57 | + return { |
| 58 | + 'success': False, |
| 59 | + 'error': f'Invalid JSON response: {str(e)}' |
| 60 | + } |
| 61 | + except Exception as e: |
| 62 | + return { |
| 63 | + 'success': False, |
| 64 | + 'error': f'Unexpected error: {str(e)}' |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | +def is_recaptcha_score_valid(score, threshold=None): |
| 69 | + if threshold is None: |
| 70 | + threshold = getattr(settings, 'RECAPTCHA_SCORE_THRESHOLD', 0.5) |
| 71 | + |
| 72 | + return score >= threshold |
0 commit comments