Refactor: отключена авторизация для отладки (REQUIRE_LOGIN=false), вернуть через REQUIRE_LOGIN=true
Made-with: Cursor
This commit is contained in:
33
app/config/middleware.py
Normal file
33
app/config/middleware.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
Мидлварь: при отключённой авторизации (REQUIRE_LOGIN=False) подставляет
|
||||
суперпользователя для анонимных запросов, чтобы меню и поле «Автор» работали.
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
_user_model = get_user_model()
|
||||
_cached_dev_user = None
|
||||
|
||||
|
||||
def get_dev_user():
|
||||
global _cached_dev_user
|
||||
if _cached_dev_user is None:
|
||||
_cached_dev_user = _user_model.objects.filter(is_superuser=True, is_active=True).first()
|
||||
return _cached_dev_user
|
||||
|
||||
|
||||
class OptionalAuthMiddleware:
|
||||
"""
|
||||
Если REQUIRE_LOGIN=False и пользователь не аутентифицирован,
|
||||
подставить первого активного суперпользователя (для отладки).
|
||||
"""
|
||||
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
if not getattr(settings, "REQUIRE_LOGIN", True) and not request.user.is_authenticated:
|
||||
user = get_dev_user()
|
||||
if user:
|
||||
request.user = user
|
||||
return self.get_response(request)
|
||||
Reference in New Issue
Block a user