99 lines
2.4 KiB
Python
99 lines
2.4 KiB
Python
"""
|
|
User authorization
|
|
"""
|
|
from typing import Optional
|
|
from bot.config import settings
|
|
from bot.modules.database.session import AsyncSessionLocal
|
|
from bot.modules.database.models import User
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def is_authorized(user_id: int) -> bool:
|
|
"""
|
|
Check user authorization
|
|
|
|
Args:
|
|
user_id: User ID
|
|
|
|
Returns:
|
|
True if user is authorized, False otherwise
|
|
"""
|
|
# Check blacklist
|
|
if user_id in settings.blocked_users_list:
|
|
return False
|
|
|
|
# Check in database
|
|
async with AsyncSessionLocal() as session:
|
|
user = await session.get(User, user_id)
|
|
if user and user.is_blocked:
|
|
return False
|
|
|
|
# If private mode is enabled, check only whitelist
|
|
if settings.PRIVATE_MODE:
|
|
# Check in configuration
|
|
if user_id in settings.authorized_users_list:
|
|
return True
|
|
|
|
# Check in database (users added via /adduser)
|
|
async with AsyncSessionLocal() as session:
|
|
user = await session.get(User, user_id)
|
|
if user and not user.is_blocked:
|
|
return True
|
|
|
|
# In private mode, access only for authorized users
|
|
return False
|
|
|
|
# If private mode is disabled
|
|
# Check whitelist (if configured)
|
|
if settings.authorized_users_list:
|
|
return user_id in settings.authorized_users_list
|
|
|
|
# If whitelist is not configured, check in database
|
|
async with AsyncSessionLocal() as session:
|
|
user = await session.get(User, user_id)
|
|
# If user exists in database and is not blocked - allow access
|
|
if user and not user.is_blocked:
|
|
return True
|
|
|
|
# By default - deny access
|
|
return False
|
|
|
|
|
|
async def is_admin(user_id: int) -> bool:
|
|
"""
|
|
Check if user is administrator
|
|
|
|
Args:
|
|
user_id: User ID
|
|
|
|
Returns:
|
|
True if administrator, False otherwise
|
|
"""
|
|
# Check in configuration
|
|
if user_id in settings.admin_ids_list:
|
|
return True
|
|
|
|
# Check in database
|
|
async with AsyncSessionLocal() as session:
|
|
user = await session.get(User, user_id)
|
|
if user and user.is_admin:
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
async def is_owner(user_id: int) -> bool:
|
|
"""
|
|
Check if user is owner
|
|
|
|
Args:
|
|
user_id: User ID
|
|
|
|
Returns:
|
|
True if owner, False otherwise
|
|
"""
|
|
return user_id == settings.OWNER_ID
|
|
|