Files
octopus/myproject/platform_admin/backends.py

82 lines
2.9 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 -*-
"""
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