Отлажен класс SessionManager

This commit is contained in:
2026-07-14 12:56:07 +03:00
parent 5c39031f04
commit 54d717369a
2 changed files with 48 additions and 12 deletions

View File

@@ -7,7 +7,7 @@
""" """
Описание класса AccountManager Описание класса AccountManager
""" """
from net.xeaf.rack.enums import AuthRejectReason
from net.xeaf.rack.models.account_model import AccountModel from net.xeaf.rack.models.account_model import AccountModel
@@ -17,14 +17,45 @@ class AccountManager:
""" """
@classmethod @classmethod
def check_account(cls, username: str) -> None: def check_account_auth(cls, account: AccountModel | None) -> AuthRejectReason | None:
""" """
Проверяет Аккаунт с указанным именем Проверяет возможность авторизации Аккаунта
:param account: Аккаунт
:return: Причина отказа в авторизации или None, если авторизация возможна
""" """
account = AccountModel.objects.filter(username=username).first()
if account is None: if account is None:
raise ValueError("Account not found") return AuthRejectReason.INVALID_USERNAME_OR_PASSWORD
if not account.is_active:
return AuthRejectReason.ACCOUNT_IS_NOT_ACTIVE
if account.joined_at is None:
return AuthRejectReason.REGISTRATION_IS_NOT_COMPLETE
return None
@classmethod
def check_username_auth(cls, username: str) -> AuthRejectReason | None:
"""
Проверяет возможность авторизации Аккаунта с заданным именем
:param username: Имя Аккаунта
:return: Причина отказа в авторизации или None, если авторизация возможна
"""
account = cls.find_by_username(username)
return cls.check_account_auth(account)
@classmethod
def find_by_username(cls, username: str) -> AccountModel | None:
"""
Возвращает Аккаунт с указанным именем
:param username: Имя Аккаунта
:return: Аккаунт или None, если Аккаунт не найден
"""
return AccountModel.objects.filter(username=username).first()
@classmethod @classmethod
def restore_account(cls, account: AccountModel) -> None: def restore_account(cls, account: AccountModel) -> None:

View File

@@ -47,16 +47,17 @@ class SessionManager[T:SessionModel]:
:return: Объект данных сессии :return: Объект данных сессии
""" """
# Отсекаем ошибки активности и регистрации
reason = AccountManager.check_username_auth(username)
if reason is not None:
cls._raise_auth_error(reason)
# noinspection PyTypeChecker # noinspection PyTypeChecker
account: AccountModel | None = authenticate(username=username, password=password) account: AccountModel | None = authenticate(username=username, password=password)
# Обрабатываем ошибки # Обрабатываем ошибки проверки пароля
if account is None: if account is None:
cls._raise_auth_error(AuthRejectReason.INVALID_USERNAME_OR_PASSWORD) cls._raise_auth_error(AuthRejectReason.INVALID_USERNAME_OR_PASSWORD)
elif not account.is_active:
cls._raise_auth_error(AuthRejectReason.ACCOUNT_IS_NOT_ACTIVE)
elif account.joined_at is None:
cls._raise_auth_error(AuthRejectReason.REGISTRATION_IS_NOT_COMPLETE)
# Создаем и возвращаем объект сессии # Создаем и возвращаем объект сессии
AccountManager.restore_account(account) AccountManager.restore_account(account)
@@ -145,11 +146,15 @@ class SessionManager[T:SessionModel]:
if cls.__model_class is None: if cls.__model_class is None:
model_path = ConfigurationManager.get_string("AUTH_SESSION_MODEL", "net_xeaf_rack.SessionModel") model_path = ConfigurationManager.get_string("AUTH_SESSION_MODEL", "net_xeaf_rack.SessionModel")
app_label, model_name = model_path.split(".") app_label, model_name = model_path.split(".")
model = apps.get_model(app_label, model_name)
try:
model = apps.get_model(app_label, model_name)
except LookupError:
model = None
# Нет класса # Нет класса
if not model: if not model:
raise ImproperlyConfigured("AUTH_SESSION_MODEL must be set in settings.py") raise ImproperlyConfigured("Correct AUTH_SESSION_MODEL must be set in settings.py")
# Некорректный класс # Некорректный класс
if not issubclass(model, SessionModel): if not issubclass(model, SessionModel):