Kishore200630 commited on
Commit
ef04581
·
verified ·
1 Parent(s): d9954fd

Update services/captcha_service.py

Browse files
Files changed (1) hide show
  1. services/captcha_service.py +86 -58
services/captcha_service.py CHANGED
@@ -1,58 +1,86 @@
1
- """
2
- Captcha verification service.
3
- Supports Google reCAPTCHA.
4
- """
5
-
6
- import requests
7
- from config import Config
8
-
9
-
10
- class CaptchaService:
11
- """Captcha verification service."""
12
-
13
- @staticmethod
14
- def verify(token: str, remote_ip: str = None) -> tuple[bool, str]:
15
- """
16
- Verify a captcha token.
17
-
18
- Args:
19
- token: Captcha token from frontend
20
- remote_ip: Client IP address (optional)
21
-
22
- Returns:
23
- Tuple of (success, error_message)
24
- """
25
- if not Config.CAPTCHA_SECRET_KEY:
26
- # Captcha not configured - allow in development
27
- return True, None
28
-
29
- if not token:
30
- return False, "Captcha token is required"
31
-
32
- try:
33
- payload = {
34
- 'secret': Config.CAPTCHA_SECRET_KEY,
35
- 'response': token,
36
- }
37
-
38
- if remote_ip:
39
- payload['remoteip'] = remote_ip
40
-
41
- response = requests.post(Config.CAPTCHA_VERIFY_URL, data=payload, timeout=10)
42
- result = response.json()
43
-
44
- if result.get('success'):
45
- return True, None
46
-
47
- # Get error codes
48
- error_codes = result.get('error-codes', [])
49
- if 'timeout-or-duplicate' in error_codes:
50
- return False, "Captcha expired. Please try again."
51
- elif 'invalid-input-response' in error_codes:
52
- return False, "Invalid captcha. Please try again."
53
- else:
54
- return False, "Captcha verification failed. Please try again."
55
-
56
- except requests.RequestException as e:
57
- print(f"Captcha verification error: {e}")
58
- return False, "Unable to verify captcha. Please try again."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Captcha verification service.
3
+ Supports Google reCAPTCHA.
4
+ Automatically skips verification for localhost/development.
5
+ """
6
+
7
+ import requests
8
+ from config import Config
9
+
10
+
11
+ class CaptchaService:
12
+ """Captcha verification service."""
13
+
14
+ # IPs that are considered localhost
15
+ LOCALHOST_IPS = {'127.0.0.1', '::1', 'localhost', '0.0.0.0', '10.0.0.0'}
16
+
17
+ @staticmethod
18
+ def is_localhost(remote_ip: str = None) -> bool:
19
+ """
20
+ Check if the request comes from localhost.
21
+
22
+ Args:
23
+ remote_ip: Client IP address
24
+
25
+ Returns:
26
+ True if localhost
27
+ """
28
+ if not remote_ip:
29
+ return False
30
+ return remote_ip in CaptchaService.LOCALHOST_IPS or remote_ip.startswith('127.') or remote_ip.startswith('192.168.') or remote_ip.startswith('10.')
31
+
32
+ @staticmethod
33
+ def verify(token: str, remote_ip: str = None) -> tuple[bool, str]:
34
+ """
35
+ Verify a captcha token.
36
+ Automatically skips verification for localhost requests.
37
+
38
+ Args:
39
+ token: Captcha token from frontend
40
+ remote_ip: Client IP address (optional)
41
+
42
+ Returns:
43
+ Tuple of (success, error_message)
44
+ """
45
+ # Skip captcha for localhost / development
46
+ if CaptchaService.is_localhost(remote_ip):
47
+ print(f"[Captcha] Skipping verification for localhost ({remote_ip})")
48
+ return True, None
49
+
50
+ if not Config.CAPTCHA_SECRET_KEY:
51
+ # Captcha not configured - allow in development
52
+ print("[Captcha] No CAPTCHA_SECRET_KEY configured, skipping verification")
53
+ return True, None
54
+
55
+ if not token:
56
+ return False, "Captcha token is required"
57
+
58
+ try:
59
+ payload = {
60
+ 'secret': Config.CAPTCHA_SECRET_KEY,
61
+ 'response': token,
62
+ }
63
+
64
+ if remote_ip:
65
+ payload['remoteip'] = remote_ip
66
+
67
+ response = requests.post(Config.CAPTCHA_VERIFY_URL, data=payload, timeout=10)
68
+ result = response.json()
69
+
70
+ if result.get('success'):
71
+ return True, None
72
+
73
+ # Get error codes
74
+ error_codes = result.get('error-codes', [])
75
+ if 'timeout-or-duplicate' in error_codes:
76
+ return False, "Captcha expired. Please try again."
77
+ elif 'invalid-input-response' in error_codes:
78
+ return False, "Invalid captcha. Please try again."
79
+ else:
80
+ return False, "Captcha verification failed. Please try again."
81
+
82
+ except requests.RequestException as e:
83
+ print(f"Captcha verification error: {e}")
84
+ # On captcha service failure, allow the request through
85
+ # rather than blocking legitimate users
86
+ return True, None