auth and rbac improves

This commit is contained in:
2025-08-20 18:33:58 +03:00
parent fe76eef273
commit fb45178396
10 changed files with 426 additions and 225 deletions

View File

@@ -234,6 +234,136 @@ class RBACOperationsImpl(RBACOperations):
return True
return False
def assign_role_to_user(self, author_id: int, role: str, community_id: int, session: Any = None) -> bool:
"""
Назначает роль пользователю в сообществе
Args:
author_id: ID автора
role: Название роли
community_id: ID сообщества
session: Сессия БД (опционально)
Returns:
True если роль была добавлена, False если уже была
"""
try:
# Поздний импорт для избежания циклических зависимостей
from orm.community import CommunityAuthor
if session:
ca = CommunityAuthor.find_author_in_community(author_id, community_id, session)
if ca:
if ca.has_role(role):
return False # Роль уже есть
ca.add_role(role)
else:
# Создаем новую запись
ca = CommunityAuthor(community_id=community_id, author_id=author_id, roles=role)
session.add(ca)
session.commit()
return True
# Используем local_session для продакшена
with local_session() as db_session:
ca = CommunityAuthor.find_author_in_community(author_id, community_id, db_session)
if ca:
if ca.has_role(role):
return False # Роль уже есть
ca.add_role(role)
else:
# Создаем новую запись
ca = CommunityAuthor(community_id=community_id, author_id=author_id, roles=role)
db_session.add(ca)
db_session.commit()
return True
except Exception as e:
logger.error(f"[assign_role_to_user] Ошибка при назначении роли {role} пользователю {author_id}: {e}")
return False
def get_user_roles_in_community(self, author_id: int, community_id: int, session: Any = None) -> list[str]:
"""
Получает роли пользователя в сообществе
Args:
author_id: ID автора
community_id: ID сообщества
session: Сессия БД (опционально)
Returns:
Список ролей пользователя
"""
try:
# Поздний импорт для избежания циклических зависимостей
from orm.community import CommunityAuthor
if session:
ca = CommunityAuthor.find_author_in_community(author_id, community_id, session)
return ca.role_list if ca else []
# Используем local_session для продакшена
with local_session() as db_session:
ca = CommunityAuthor.find_author_in_community(author_id, community_id, db_session)
return ca.role_list if ca else []
except Exception as e:
logger.error(f"[get_user_roles_in_community] Ошибка при получении ролей: {e}")
return []
def remove_role_from_user(self, author_id: int, role: str, community_id: int, session: Any = None) -> bool:
"""
Удаляет роль у пользователя в сообществе
Args:
author_id: ID автора
role: Название роли
community_id: ID сообщества
session: Сессия БД (опционально)
Returns:
True если роль была удалена, False если её не было
"""
try:
# Поздний импорт для избежания циклических зависимостей
from orm.community import CommunityAuthor
if session:
ca = CommunityAuthor.find_author_in_community(author_id, community_id, session)
if ca and ca.has_role(role):
ca.remove_role(role)
# Если ролей не осталось, удаляем запись
if ca.role_list:
session.delete(ca)
session.commit()
return True
return False
# Используем local_session для продакшена
with local_session() as db_session:
ca = CommunityAuthor.find_author_in_community(author_id, community_id, db_session)
if ca and ca.has_role(role):
ca.remove_role(role)
# Если ролей не осталось, удаляем запись
if not ca.role_list:
db_session.delete(ca)
db_session.commit()
return True
return False
except Exception as e:
logger.error(f"[remove_role_from_user] Ошибка при удалении роли {role} у пользователя {author_id}: {e}")
return False
class CommunityAuthorQueriesImpl(CommunityAuthorQueries):
"""Конкретная реализация запросов CommunityAuthor через поздний импорт"""