import time import hmac import hashlib import json import logging from urllib.parse import unquote from fastapi import Request, HTTPException from config import BOT_TOKEN, MAX_INITDATA_AGE logger = logging.getLogger(__name__) async def verify_telegram_initdata(init_data: str): """Проверяет подпись initData от Telegram с проверкой срока действия""" try: # Парсим initData data = {} for chunk in init_data.split('&'): if '=' in chunk: key, value = chunk.split('=', 1) data[key] = unquote(value) # Извлекаем hash received_hash = data.pop('hash', '') if not received_hash: raise HTTPException(401, "Hash not found in initData") # Проверяем auth_date (не старше MAX_INITDATA_AGE из config) auth_date_str = data.get('auth_date', '0') try: auth_date = int(auth_date_str) current_time = int(time.time()) if current_time - auth_date > MAX_INITDATA_AGE: raise HTTPException(401, "initData expired") if auth_date > current_time + 60: raise HTTPException(401, "initData from future") except ValueError: raise HTTPException(401, "Invalid auth_date") # Сортируем ключи и создаем строку для проверки check_arr = [] for key in sorted(data.keys()): check_arr.append(f"{key}={data[key]}") check_string = '\n'.join(check_arr) # Создаем секретный ключ secret_key = hmac.new( 'WebAppData'.encode(), BOT_TOKEN.encode(), hashlib.sha256 ).digest() # Вычисляем hash calculated_hash = hmac.new( secret_key, check_string.encode(), hashlib.sha256 ).hexdigest() if not hmac.compare_digest(calculated_hash, received_hash): raise HTTPException(401, "Invalid initData signature") # Извлекаем данные пользователя user_data_str = data.get('user', '{}') try: user_data = json.loads(user_data_str) except json.JSONDecodeError: raise HTTPException(401, "Invalid user data JSON") user_id = user_data.get('id') username = user_data.get('username', '') if not user_id: raise HTTPException(401, "User ID not found in initData") return user_id, username except HTTPException: raise except Exception as e: logger.error(f"Auth error: {str(e)}", exc_info=True) raise HTTPException(401, "Invalid initData") async def require_auth(request: Request): """Извлекает и проверяет авторизацию из запроса. Два режима: 1. X-Admin-Token: — админка через браузер (26.09.2026) 2. Authorization: tma — Telegram Mini App Приоритет: 1. X-Admin-Token — если есть, проверяем JWT. 2. Authorization: tma — основной для Mini App. 3. X-Telegram-InitData — старый способ. 4. query-параметр initData — fallback для deleteFeedPost. """ # ============ Режим 1: админ-токен ============ admin_token = request.headers.get('X-Admin-Token', '').strip() if admin_token: try: from routers.admin_auth import verify_jwt from config import ADMIN_TOKEN_USER_ID payload = verify_jwt(admin_token) # Возвращаем специальный ID для admin-токена return ADMIN_TOKEN_USER_ID, payload.get('login', 'admin') except ValueError as e: logger.warning(f"Admin token invalid: {e}") raise HTTPException(401, "Invalid admin token") # ============ Режим 2: Telegram initData ============ init_data = '' # 2.1. Authorization: tma auth_header = request.headers.get('Authorization', '') if auth_header.startswith('tma '): init_data = auth_header[4:].strip() # 2.2. X-Telegram-InitData (старый способ) if not init_data: init_data = request.headers.get('X-Telegram-InitData', '') # 2.3. Query-параметр (fallback, нужен для deleteFeedPost) if not init_data: init_data = request.query_params.get('initData', '') if not init_data: raise HTTPException( 401, "Authorization required. Pass 'X-Admin-Token' or " "'Authorization: tma ' or 'X-Telegram-InitData' " "or query parameter 'initData'" ) user_id, username = await verify_telegram_initdata(init_data) return user_id, username