Добавление папки platform_admin
This commit is contained in:
81
myproject/platform_admin/backends.py
Normal file
81
myproject/platform_admin/backends.py
Normal file
@@ -0,0 +1,81 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Authentication backend для PlatformAdmin.
|
||||
|
||||
Этот backend используется для аутентификации администраторов платформы.
|
||||
Работает на public домене, а также на tenant доменах для суперадминов.
|
||||
"""
|
||||
from django.contrib.auth.backends import ModelBackend
|
||||
from django.db import connection
|
||||
|
||||
|
||||
class PlatformAdminBackend(ModelBackend):
|
||||
"""
|
||||
Backend аутентификации для PlatformAdmin.
|
||||
|
||||
Особенности:
|
||||
- На public домене: аутентифицирует любого PlatformAdmin
|
||||
- На tenant домене: аутентифицирует только PlatformAdmin с is_superuser=True
|
||||
(для поддержки и отладки клиентов)
|
||||
|
||||
Обычные PlatformAdmin (без is_superuser) не могут логиниться на tenant доменах.
|
||||
"""
|
||||
|
||||
def authenticate(self, request, username=None, password=None, **kwargs):
|
||||
"""
|
||||
Аутентификация PlatformAdmin по email и паролю.
|
||||
|
||||
Args:
|
||||
request: HTTP запрос
|
||||
username: Email администратора
|
||||
password: Пароль
|
||||
|
||||
Returns:
|
||||
PlatformAdmin если аутентификация успешна, иначе None
|
||||
"""
|
||||
from platform_admin.models import PlatformAdmin
|
||||
|
||||
if username is None or password is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
# Всегда читаем из default (public schema)
|
||||
user = PlatformAdmin.objects.using('default').get(email=username)
|
||||
except PlatformAdmin.DoesNotExist:
|
||||
# Run the default password hasher once to reduce the timing
|
||||
# difference between an existing and a non-existing user
|
||||
PlatformAdmin().set_password(password)
|
||||
return None
|
||||
|
||||
if not user.check_password(password):
|
||||
return None
|
||||
|
||||
if not self.user_can_authenticate(user):
|
||||
return None
|
||||
|
||||
# На tenant домене — только суперадмин может логиниться
|
||||
schema_name = getattr(connection, 'schema_name', 'public')
|
||||
if schema_name != 'public' and not user.is_superuser:
|
||||
return None
|
||||
|
||||
return user
|
||||
|
||||
def get_user(self, user_id):
|
||||
"""
|
||||
Получение PlatformAdmin по ID.
|
||||
|
||||
Всегда читает из public schema.
|
||||
"""
|
||||
from platform_admin.models import PlatformAdmin
|
||||
|
||||
try:
|
||||
return PlatformAdmin.objects.using('default').get(pk=user_id)
|
||||
except PlatformAdmin.DoesNotExist:
|
||||
return None
|
||||
|
||||
def user_can_authenticate(self, user):
|
||||
"""
|
||||
Проверка что пользователь активен.
|
||||
"""
|
||||
is_active = getattr(user, 'is_active', None)
|
||||
return is_active or is_active is None
|
||||
Reference in New Issue
Block a user