Files
ucvl-zonghengjia-open-source/backend/accounts/middleware.py
T

109 lines
4.8 KiB
Python
Raw Permalink Normal View History

import hashlib
import hmac
import ipaddress
import json
from datetime import timedelta
from django.conf import settings
from django.db import transaction
from django.http import HttpResponse
from django.utils import timezone
from .models import LoginAttempt
class LoginRateLimitMiddleware:
watched_paths = {"/login/", "/admin/login/", "/api/v1/client/login/", "/auth/wecom/start/", "/account/wecom/unbind/"}
max_failures = 7
window = timedelta(minutes=15)
block_for = timedelta(minutes=15)
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
watched = request.method == "POST" and request.path in self.watched_paths
key = self._key_for_request(request) if watched else None
if watched and self._is_blocked(key):
response = HttpResponse("登录尝试过多,请 15 分钟后重试。", status=429, content_type="text/plain; charset=utf-8")
response["Retry-After"] = "900"
return response
response = self.get_response(request)
if watched:
if self._credential_was_accepted(request, response):
LoginAttempt.objects.filter(key=key).delete()
elif self._is_credential_failure(request, response):
self._record_failure(key)
return response
@staticmethod
def _credential_was_accepted(request, response):
if request.path == "/api/v1/client/login/":
# The client login view returns 403 only after the supplied
# credentials have been verified. Account, subscription and
# device policy denials must not be treated as password failures.
return 200 <= response.status_code < 300 or response.status_code == 403
return 300 <= response.status_code < 400 and request.user.is_authenticated
@staticmethod
def _is_credential_failure(request, response):
if request.path in {"/auth/wecom/start/", "/account/wecom/unbind/"}:
return response.status_code == 403
if request.path == "/api/v1/client/login/":
return response.status_code in {400, 401}
# Django's HTML login forms render validation errors with HTTP 200.
# CSRF/policy errors (403), redirects and server errors are excluded.
return response.status_code in {200, 400, 401} and not request.user.is_authenticated
@staticmethod
def _client_ip(request):
candidate = request.META.get("HTTP_X_REAL_IP") or request.META.get("REMOTE_ADDR") or "unknown"
try:
return str(ipaddress.ip_address(candidate.strip()))
except ValueError:
return "unknown"
@staticmethod
def _login_identifier(request):
if request.path in {"/auth/wecom/start/", "/account/wecom/unbind/"}:
return "wecom-account:" + str(request.user.pk if request.user.is_authenticated else "anonymous")
candidate = ""
if request.path == "/api/v1/client/login/":
try:
if len(request.body) > 16 * 1024:
return "unknown"
payload = json.loads(request.body or b"{}")
candidate = str(payload.get("login", "")) if isinstance(payload, dict) else ""
except (TypeError, ValueError, json.JSONDecodeError, UnicodeDecodeError):
candidate = ""
else:
candidate = str(request.POST.get("username") or request.POST.get("login") or "")
normalized = candidate.strip().casefold()[:254]
return normalized or "unknown"
def _key_for_request(self, request):
# Scope the protection to one account at one network address. Offices,
# hotels and mobile hotspots commonly place many legitimate users
# behind the same public IP, so an IP-only key creates shared lockouts.
value = f"login:{self._client_ip(request)}:{self._login_identifier(request)}".encode()
return hmac.new(settings.SECRET_KEY.encode(), value, hashlib.sha256).hexdigest()
def _is_blocked(self, key):
attempt = LoginAttempt.objects.filter(key=key).only("blocked_until").first()
return bool(attempt and attempt.blocked_until and attempt.blocked_until > timezone.now())
def _record_failure(self, key):
now = timezone.now()
with transaction.atomic():
attempt, _created = LoginAttempt.objects.select_for_update().get_or_create(key=key)
if now - attempt.window_started_at > self.window:
attempt.failures = 0
attempt.window_started_at = now
attempt.blocked_until = None
attempt.failures += 1
if attempt.failures >= self.max_failures:
attempt.blocked_until = now + self.block_for
attempt.save(update_fields=["failures", "window_started_at", "blocked_until", "updated_at"])