Files
filwordspl-backend/auth.py
T
Drobysh a3f7d9521f feat(auth): авторизация Pleily — JWT + device_id + auth_identities
Backend:
- POST /auth/device — анонимный вход по device_id (UUID)
- GET /auth/me — текущий юзер
- DELETE /me — удаление аккаунта (Apple требует)

БД:
- users.source TEXT DEFAULT 'telegram'
- users.device_id UUID UNIQUE
- users.apple_id TEXT UNIQUE
- app_user_id_seq (START -1 INCREMENT -1)
- auth_identities (provider, provider_uid, user_id)

Auth:
- JWT через PyJWT, APP_JWT_SECRET из .env
- Authorization: Bearer <token> в require_auth
- Rate limit /auth/device (5/60)

Отрицательные telegram_id для Pleily-юзеров.
2026-10-07 11:21:18 +00:00

148 lines
5.4 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.
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: <jwt> — админка через браузер (26.09.2026)
2. Authorization: Bearer <jwt> — Pleily (07.10.2026)
3. Authorization: tma <initData> — Telegram Mini App
4. X-Telegram-InitData — старый способ
5. 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: Bearer JWT (Pleily) ============
# 🔧 НОВОЕ (07.10.2026): app_jwt_auth —
# мобильное приложение Pleily ходит с Authorization: Bearer <JWT>.
# verify_app_jwt возвращает payload с user_id (отрицательный для Pleily).
auth_header = request.headers.get('Authorization', '')
if auth_header.startswith('Bearer '):
from routers.app_auth import verify_app_jwt
token = auth_header[7:].strip()
payload = verify_app_jwt(token)
user_id = int(payload.get('user_id'))
return user_id, f"app_{user_id}"
# ============ Режим 3: Telegram initData ============
init_data = ''
# 3.1. Authorization: tma <initData>
if auth_header.startswith('tma '):
init_data = auth_header[4:].strip()
# 3.2. X-Telegram-InitData (старый способ)
if not init_data:
init_data = request.headers.get('X-Telegram-InitData', '')
# 3.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 <initData>' or 'X-Telegram-InitData' "
"or query parameter 'initData'"
)
user_id, username = await verify_telegram_initdata(init_data)
return user_id, username