Spaces:
Sleeping
Sleeping
Upload backend/core/middleware.py with huggingface_hub
Browse files- backend/core/middleware.py +57 -0
backend/core/middleware.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from django.utils.deprecation import MiddlewareMixin
|
| 5 |
+
from django.http import HttpRequest, HttpResponse
|
| 6 |
+
from .models import AuditLog
|
| 7 |
+
|
| 8 |
+
class SecurityHeadersMiddleware(MiddlewareMixin):
|
| 9 |
+
def process_response(self, request: HttpRequest, response: HttpResponse):
|
| 10 |
+
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
| 11 |
+
response.headers.setdefault("Referrer-Policy", "no-referrer-when-downgrade")
|
| 12 |
+
response.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
|
| 13 |
+
# CSP tối giản; mở rộng khi cần
|
| 14 |
+
response.headers.setdefault("Content-Security-Policy", "default-src 'self'; img-src 'self' data:;")
|
| 15 |
+
return response
|
| 16 |
+
|
| 17 |
+
class AuditLogMiddleware(MiddlewareMixin):
|
| 18 |
+
def process_request(self, request: HttpRequest):
|
| 19 |
+
request._audit_start = time.perf_counter()
|
| 20 |
+
|
| 21 |
+
def process_response(self, request: HttpRequest, response: HttpResponse):
|
| 22 |
+
try:
|
| 23 |
+
path = request.path[:300]
|
| 24 |
+
query = request.META.get("QUERY_STRING", "")[:500]
|
| 25 |
+
ua = request.META.get("HTTP_USER_AGENT", "")[:300]
|
| 26 |
+
ip = request.META.get("REMOTE_ADDR")
|
| 27 |
+
latency_ms = None
|
| 28 |
+
start = getattr(request, "_audit_start", None)
|
| 29 |
+
if start is not None:
|
| 30 |
+
latency_ms = (time.perf_counter() - start) * 1000
|
| 31 |
+
|
| 32 |
+
intent = ""
|
| 33 |
+
confidence = None
|
| 34 |
+
data: Any = getattr(response, "data", None)
|
| 35 |
+
if isinstance(data, dict):
|
| 36 |
+
intent = str(data.get("intent") or "")[:50]
|
| 37 |
+
confidence_value = data.get("confidence")
|
| 38 |
+
try:
|
| 39 |
+
confidence = float(confidence_value) if confidence_value is not None else None
|
| 40 |
+
except (TypeError, ValueError):
|
| 41 |
+
confidence = None
|
| 42 |
+
|
| 43 |
+
AuditLog.objects.create(
|
| 44 |
+
path=path,
|
| 45 |
+
query=query,
|
| 46 |
+
user_agent=ua,
|
| 47 |
+
ip=ip,
|
| 48 |
+
status=response.status_code,
|
| 49 |
+
intent=intent,
|
| 50 |
+
confidence=confidence,
|
| 51 |
+
latency_ms=latency_ms,
|
| 52 |
+
)
|
| 53 |
+
except Exception:
|
| 54 |
+
# Không làm hỏng request nếu ghi log lỗi
|
| 55 |
+
pass
|
| 56 |
+
return response
|
| 57 |
+
|