Files
api/app/middleware.py
2025-12-30 11:27:14 +07:00

68 lines
1.9 KiB
Python

from urllib.parse import urlparse
from django.http import JsonResponse
import threading
_thread_locals = threading.local()
def get_current_user():
"""
Retrieves the current user from thread-local storage.
"""
return getattr(_thread_locals, 'user', None)
class CurrentUserMiddleware:
"""
Middleware to store the current user in thread-local storage.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Store the user in thread-local storage
_thread_locals.user = request.user if hasattr(request, 'user') and request.user.is_authenticated else None
response = self.get_response(request)
# Clean up the thread-local storage after the request is finished
if hasattr(_thread_locals, 'user'):
del _thread_locals.user
return response
ALLOWED_ORIGINS = [
"http://localhost:3000",
"https://biz.utopia.com.vn",
"https://datamodel.bigdatatech.vn"
]
ALLOWED_DOMAIN_SUFFIXES = [
".utopia.com.vn"
]
ALLOWED_HOST = [
"localhost:8000",
"api.utopia.com.vn",
"dev.api.utopia.com.vn"
]
class BlockUnauthorizedOriginsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
origin = request.headers.get("Origin")
host = request.get_host()
if origin:
parsed = urlparse(origin)
domain = parsed.hostname
if origin not in ALLOWED_ORIGINS and not any(
domain.endswith(suffix) for suffix in ALLOWED_DOMAIN_SUFFIXES
):
return JsonResponse({"detail": "Forbidden origin"}, status=4.3)
if not origin and host not in ALLOWED_HOST:
return JsonResponse({"detail": "Direct access not allowed"}, status=403)
return self.get_response(request)