Files
octopus/myproject/myproject/admin_access_middleware.py

47 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
Middleware для ограничения доступа к админке Django на поддоменах тенантов.
SECURITY: Этот middleware обеспечивает дополнительный слой защиты,
блокируя доступ владельцев тенантов к /admin/ даже если у них
случайно установлен is_staff=True.
Правила доступа:
- На tenant поддоменах (shop1.localhost): только is_superuser=True может входить в /admin/
- На public схеме (localhost): обычные правила Django (is_staff=True достаточно)
- Суперпользователи имеют доступ везде
"""
from django.http import HttpResponseForbidden
class TenantAdminAccessMiddleware:
"""
Дополнительный слой безопасности: блокирует доступ владельцев тенантов к /admin/
даже если у них случайно установлен is_staff=True.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Проверяем, это admin URL?
if request.path.startswith('/admin/'):
from django.db import connection
# Если мы в tenant схеме (не public)
if hasattr(connection, 'tenant') and connection.tenant:
# Проверяем: это не public схема?
if connection.tenant.schema_name != 'public':
# Проверяем наличие атрибута user (добавляется AuthenticationMiddleware)
if hasattr(request, 'user'):
# Если пользователь авторизован, но НЕ суперпользователь - блокируем
if request.user.is_authenticated and not request.user.is_superuser:
return HttpResponseForbidden(
"Доступ запрещен. Только системные администраторы могут "
"заходить в админ-панель на поддоменах тенантов. "
"Используйте панель управления тенанта."
)
response = self.get_response(request)
return response