Files
igny8/backend/igny8_core/auth/backends.py
2025-12-09 14:28:44 +00:00

36 lines
1.3 KiB
Python

"""
Custom Authentication Backend - No Caching
Prevents cross-request user contamination by disabling Django's default user caching
"""
from django.contrib.auth.backends import ModelBackend
class NoCacheModelBackend(ModelBackend):
"""
Custom authentication backend that disables user object caching.
Django's default ModelBackend caches the user object in thread-local storage,
which can cause cross-request contamination when the same worker process
handles requests from different users.
This backend forces a fresh DB query on EVERY request to prevent user swapping.
"""
def get_user(self, user_id):
"""
Get user from database WITHOUT caching.
This overrides the default behavior which caches user objects
at the process level, causing session contamination.
"""
from django.contrib.auth import get_user_model
UserModel = get_user_model()
try:
# CRITICAL: Use select_related to load account/plan in ONE query
# But do NOT cache the result - return fresh object every time
user = UserModel.objects.select_related('account', 'account__plan').get(pk=user_id)
return user
except UserModel.DoesNotExist:
return None