-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathverification.py
79 lines (66 loc) · 2.78 KB
/
verification.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from datetime import timedelta
from functools import wraps
from django.conf import settings
from django.utils import timezone
from user.models import LoginRequest
import requests
def check_recaptcha(view_func):
@wraps(view_func)
def _wrapped_view(view, request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
if not settings.GOOGLE_RECAPTCHA_SECRET_KEY:
request.recaptcha_is_valid = True
else:
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()
if result['success']:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
return view_func(view, request, *args, **kwargs)
return _wrapped_view
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def reset_tries(request):
client_ip = get_client_ip(request)
login_request = LoginRequest.objects.get(ip=client_ip)
login_request.reset_tries()
login_request.save()
def check_client_ip(view_func):
@wraps(view_func)
def _wrapped_view(view, request, *args, **kwargs):
request.client_req_is_valid = None
if request.method == 'POST':
client_ip = get_client_ip(request)
request_time = timezone.now()
print(request_time)
try:
login_request = LoginRequest.objects.get(ip=client_ip)
latest_request = login_request.latest_request
if request_time - latest_request < timedelta(minutes=5):
login_request.login_tries += 1
else:
login_request.reset_tries()
if login_request.login_tries < getattr(settings, 'LOGIN_TRIES', 4):
login_request.latest_request = request_time
login_request.save()
except LoginRequest.DoesNotExist:
login_request = LoginRequest.objects.create(ip=client_ip, latest_request=request_time)
login_request.save()
if login_request.login_tries < getattr(settings, 'LOGIN_TRIES', 4):
request.client_req_is_valid = True
else:
request.client_req_is_valid = False
return view_func(view, request, *args, **kwargs)
return _wrapped_view