diff --git a/.gitignore b/.gitignore index 99b55cc..fb38b46 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ uploads/ .DS_Store .env.save .env.* +*.backup_* +*.sql +*.backup* diff --git a/auth.py b/auth.py index c4fb494..d8d38a7 100644 --- a/auth.py +++ b/auth.py @@ -89,15 +89,12 @@ async def verify_telegram_initdata(init_data: str): 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. X-Admin-Token: — админка через браузер (26.09.2026) + 2. Authorization: Bearer — Pleily (07.10.2026) + 3. Authorization: tma — Telegram Mini App + 4. X-Telegram-InitData — старый способ + 5. query-параметр initData — fallback для deleteFeedPost """ # ============ Режим 1: админ-токен ============ admin_token = request.headers.get('X-Admin-Token', '').strip() @@ -112,19 +109,30 @@ async def require_auth(request: Request): logger.warning(f"Admin token invalid: {e}") raise HTTPException(401, "Invalid admin token") - # ============ Режим 2: Telegram initData ============ + # ============ Режим 2: Bearer JWT (Pleily) ============ + # 🔧 НОВОЕ (07.10.2026): app_jwt_auth — + # мобильное приложение Pleily ходит с Authorization: Bearer . + # 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 = '' - # 2.1. Authorization: tma - auth_header = request.headers.get('Authorization', '') + # 3.1. Authorization: tma if auth_header.startswith('tma '): init_data = auth_header[4:].strip() - # 2.2. X-Telegram-InitData (старый способ) + # 3.2. X-Telegram-InitData (старый способ) if not init_data: init_data = request.headers.get('X-Telegram-InitData', '') - # 2.3. Query-параметр (fallback, нужен для deleteFeedPost) + # 3.3. Query-параметр (fallback, нужен для deleteFeedPost) if not init_data: init_data = request.query_params.get('initData', '') diff --git a/config.py b/config.py index 20ce11c..0f328f1 100644 --- a/config.py +++ b/config.py @@ -93,4 +93,7 @@ FEED_TARGET_LANGUAGES = ["pl", "ru", "uk", "en"] # Логин/пароль для входа в админку через браузер. ADMIN_LOGIN = os.getenv("ADMIN_LOGIN", "admin") ADMIN_PASSWORD_HASH = os.getenv("ADMIN_PASSWORD_HASH", "") -ADMIN_JWT_SECRET = os.getenv("ADMIN_JWT_SECRET", "") \ No newline at end of file +ADMIN_JWT_SECRET = os.getenv("ADMIN_JWT_SECRET", "") + +# 🔧 НОВОЕ (07.10.2026): app_jwt_secret — JWT для Pleily +APP_JWT_SECRET = os.getenv("APP_JWT_SECRET", "") \ No newline at end of file diff --git a/database.py b/database.py index 46fbc40..be399eb 100644 --- a/database.py +++ b/database.py @@ -1246,6 +1246,95 @@ async def init_db(): """) logger.info("Table word_usage initialized") + # ============ 🔧 НОВОЕ (07.10.2026): pleily_auth — + # поддержка авторизации мобильного приложения Pleily. + # - source: откуда пришёл юзер ('telegram' | 'pleily_device' | 'pleily_apple') + # - device_id: UUID устройства (анонимный вход) + # - apple_id: Apple ID (потом, для привязки прогресса) + # - app_user_id_seq: sequence для отрицательных user_id (Pleily-юзеры) + # - auth_identities: связка provider+provider_uid → user_id + # ============================================================ + + # source + col_exists = await conn.fetchval(""" + SELECT 1 FROM information_schema.columns + WHERE table_name = 'users' AND column_name = 'source' + """) + if not col_exists: + await conn.execute(""" + ALTER TABLE users ADD COLUMN source TEXT DEFAULT 'telegram' + """) + await conn.execute(""" + UPDATE users SET source = 'telegram' WHERE source IS NULL + """) + logger.info("Added source column to users (Pleily)") + + # device_id + col_exists = await conn.fetchval(""" + SELECT 1 FROM information_schema.columns + WHERE table_name = 'users' AND column_name = 'device_id' + """) + if not col_exists: + await conn.execute(""" + ALTER TABLE users ADD COLUMN device_id UUID + """) + await conn.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS idx_users_device_id + ON users(device_id) WHERE device_id IS NOT NULL + """) + logger.info("Added device_id column to users (Pleily)") + + # apple_id + col_exists = await conn.fetchval(""" + SELECT 1 FROM information_schema.columns + WHERE table_name = 'users' AND column_name = 'apple_id' + """) + if not col_exists: + await conn.execute(""" + ALTER TABLE users ADD COLUMN apple_id TEXT + """) + await conn.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS idx_users_apple_id + ON users(apple_id) WHERE apple_id IS NOT NULL + """) + logger.info("Added apple_id column to users (Pleily)") + + # app_user_id_seq — sequence для отрицательных user_id + await conn.execute(""" + CREATE SEQUENCE IF NOT EXISTS app_user_id_seq + START -1 + INCREMENT -1 + MINVALUE -9223372036854775808 + MAXVALUE -1 + """) + logger.info("Table app_user_id_seq initialized (Pleily)") + + # auth_identities — связка provider+provider_uid → user_id + await conn.execute(""" + CREATE TABLE IF NOT EXISTS auth_identities ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES users(telegram_id) ON DELETE CASCADE, + provider TEXT NOT NULL, + provider_uid TEXT NOT NULL, + created_at TIMESTAMP DEFAULT NOW(), + UNIQUE(provider, provider_uid) + ) + """) + await conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_auth_identities_user + ON auth_identities(user_id) + """) + + # Backfill: для существующих telegram-юзеров создаём identity + await conn.execute(""" + INSERT INTO auth_identities (user_id, provider, provider_uid) + SELECT telegram_id, 'telegram', telegram_id::text + FROM users + WHERE telegram_id > 0 + ON CONFLICT DO NOTHING + """) + logger.info("Table auth_identities initialized (Pleily)") + await conn.execute("CREATE INDEX IF NOT EXISTS idx_sentences_level_number ON sentences(level, sentence_number)") # Оставляем score-индексы (не дубли) await conn.execute("CREATE INDEX IF NOT EXISTS idx_user_progress_score ON user_progress(score DESC)") diff --git a/main.py b/main.py index 6262e34..f8f9ce3 100644 --- a/main.py +++ b/main.py @@ -14,6 +14,7 @@ from database import init_db from routers import users, game, hints, leaderboard, sentences, achievements, wordquiz, bubblewords, pronunciation, assistant, learning, tts, typing, teacher, support, admin, feed, admin_content from routers import lectures, admin_auth, admin_wordsearch, admin_users from routers import admin_ai # 🔧 НОВОЕ +from routers import app_auth # 🆕 Pleily auth from routers.sentences import init_sentences from routers.achievements import init_achievements from routers.learning_data import init_learning_data @@ -91,6 +92,9 @@ class RateLimiter: # 🔧 ФИКС (22.09.2026): дорогой AI-эндпоинт без лимита выжигал бюджет. "/learning/analytics": {"max_requests": 5, "window": 60}, "/learning/practice/start": {"max_requests": 10, "window": 60}, + # 🆕 Pleily (07.10.2026): лимит на вход по device_id. + # Защищает от спама создания новых юзеров. + "/auth/device": {"max_requests": 5, "window": 60}, } self._cleanup_task = None @@ -370,6 +374,7 @@ app.include_router(admin_auth.router) app.include_router(admin_wordsearch.router) app.include_router(admin_users.router) app.include_router(admin_ai.router) # 🔧 НОВОЕ +app.include_router(app_auth.router) # 🆕 Pleily # ============ Базовые эндпоинты ============ diff --git a/requirements.txt b/requirements.txt index c139005..c9e54c7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -37,3 +37,4 @@ urllib3==2.7.0 uvicorn==0.51.0 yarl==1.24.5 pdfplumber==0.11.10 +PyJWT==2.15.1 diff --git a/routers/app_auth.py b/routers/app_auth.py new file mode 100644 index 0000000..0d1b629 --- /dev/null +++ b/routers/app_auth.py @@ -0,0 +1,245 @@ +""" +App Auth Router — авторизация мобильного приложения Pleily. + +Поддерживает: +- Анонимный вход по device_id (UUID) → выдаёт JWT на 365 дней. +- Привязка Apple ID (позже). +- Удаление аккаунта (требование Apple App Store). + +Pleily-юзеры имеют ОТРИЦАТЕЛЬНЫЙ telegram_id (из sequence app_user_id_seq). +Telegram-юзеры сохраняют свои положительные telegram_id. + +Все Pleily-юзеры изолированы в auth_identities: связка (provider, provider_uid) +указывает на users.telegram_id. Так один юзер может иметь несколько способов входа. + +Эндпоинты: +- POST /auth/device — вход по device_id +- GET /auth/me — текущий юзер (для тестов) +- DELETE /me — удаление аккаунта (Apple требует) + +🔧 НОВОЕ (07.10.2026): pleily_auth — первая версия. +""" +import logging +import uuid +from datetime import datetime, timezone, timedelta +from typing import Optional + +import asyncpg +import jwt +from fastapi import APIRouter, Request, HTTPException, Depends + +from auth import require_auth +from database import get_pool +from config import APP_JWT_SECRET + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/auth", tags=["app-auth"]) + +# JWT настройки +JWT_ALGORITHM = "HS256" +JWT_TTL_DAYS = 365 +JWT_TTL = timedelta(days=JWT_TTL_DAYS) + + +# ============ JWT HELPERS ============ + +def make_app_jwt(user_id: int) -> str: + """Создаёт JWT для Pleily-юзера. Payload: {user_id, exp, iat}.""" + if not APP_JWT_SECRET: + raise RuntimeError("APP_JWT_SECRET not configured") + + now = datetime.now(timezone.utc) + payload = { + "user_id": int(user_id), + "iat": int(now.timestamp()), + "exp": int((now + JWT_TTL).timestamp()), + } + return jwt.encode(payload, APP_JWT_SECRET, algorithm=JWT_ALGORITHM) + + +def verify_app_jwt(token: str) -> dict: + """Проверяет JWT, возвращает payload. Бросает ValueError если невалиден.""" + if not APP_JWT_SECRET: + raise ValueError("APP_JWT_SECRET not configured") + + try: + payload = jwt.decode(token, APP_JWT_SECRET, algorithms=[JWT_ALGORITHM]) + except jwt.ExpiredSignatureError: + raise ValueError("Token expired") + except jwt.InvalidTokenError as e: + raise ValueError(f"Invalid token: {e}") + + if "user_id" not in payload: + raise ValueError("user_id missing in token payload") + + return payload + + +# ============ ВСПОМОГАТЕЛЬНЫЕ ============ + +async def _find_user_by_device(conn, device_id: str) -> Optional[int]: + """Ищет user_id по (provider='device', provider_uid=device_id).""" + row = await conn.fetchrow(""" + SELECT user_id FROM auth_identities + WHERE provider = 'device' AND provider_uid = $1 + """, device_id) + return row["user_id"] if row else None + + +async def _create_app_user(conn, device_id: str) -> int: + """ + Создаёт нового Pleily-юзера с отрицательным telegram_id + (из sequence app_user_id_seq) и связкой auth_identities. + Возвращает telegram_id (отрицательный). + """ + # nextval из sequence app_user_id_seq даёт -1, -2, -3, ... + uid_row = await conn.fetchrow("SELECT nextval('app_user_id_seq') AS uid") + uid = uid_row["uid"] + + # Создаём юзера в users + await conn.execute(""" + INSERT INTO users (telegram_id, username, source) + VALUES ($1, $2, 'app') + """, uid, f"app_user_{abs(uid)}") + + # Создаём identity + await conn.execute(""" + INSERT INTO auth_identities (user_id, provider, provider_uid) + VALUES ($1, 'device', $2) + """, uid, device_id) + + logger.info(f"[app_auth] created Pleily user: telegram_id={uid}, device={device_id}") + return uid + + +# ============ ЭНДПОИНТЫ ============ + +@router.post("/device") +async def auth_device(request: Request): + """ + Вход по device_id. + Body: {"device_id": "uuid-string"} + + Если юзер с таким device_id уже есть — выдаёт новый JWT. + Если нет — создаёт нового Pleily-юзера и выдаёт JWT. + + Returns: {"status": "ok", "token": "...", "user_id": -1} + """ + body = await request.json() + device_id_raw = (body.get("device_id") or "").strip() + + if not device_id_raw: + raise HTTPException(400, "device_id is required") + + # Валидация UUID + try: + device_uuid = uuid.UUID(device_id_raw) + except (ValueError, AttributeError, TypeError): + raise HTTPException(400, "device_id must be a valid UUID") + + device_id_str = str(device_uuid) + + pool = await get_pool() + async with pool.acquire() as conn: + # Пытаемся найти существующего юзера + user_id = await _find_user_by_device(conn, device_id_str) + + if user_id is None: + # Создаём нового — в транзакции, чтобы nextval + INSERT были атомарны + try: + async with conn.transaction(): + user_id = await _create_app_user(conn, device_id_str) + except asyncpg.UniqueViolationError: + # 🔧 Гонка: два параллельных запроса с одним device_id. + # Один вставил, второй словил UniqueViolation на (provider, provider_uid). + # Просто перечитываем — юзер уже есть. + logger.warning( + f"[app_auth] race on device_id={device_id_str}, retrying SELECT" + ) + user_id = await _find_user_by_device(conn, device_id_str) + if user_id is None: + raise HTTPException(500, "Failed to create or find user") + + token = make_app_jwt(user_id) + logger.info(f"[app_auth] login device={device_id_str} → user_id={user_id}") + + return { + "status": "ok", + "token": token, + "user_id": user_id, + } + + +@router.get("/me") +async def auth_me(request: Request): + """ + Возвращает данные текущего Pleily-юзера. Для тестов и отладки. + + Требует Authorization: Bearer . + """ + user_id, _username = await require_auth(request) + + pool = await get_pool() + async with pool.acquire() as conn: + row = await conn.fetchrow(""" + SELECT telegram_id, username, source, app_language, current_level, created_at + FROM users WHERE telegram_id = $1 + """, user_id) + + if not row: + raise HTTPException(404, "User not found") + + # Получаем identities юзера (для диагностики) + identities_rows = await conn.fetch(""" + SELECT provider, provider_uid, created_at + FROM auth_identities WHERE user_id = $1 + ORDER BY created_at + """, user_id) + + return { + "user_id": row["telegram_id"], + "username": row["username"], + "source": row["source"], + "app_language": row["app_language"], + "current_level": row["current_level"], + "created_at": row["created_at"].isoformat() if row["created_at"] else None, + "identities": [ + { + "provider": r["provider"], + "provider_uid": r["provider_uid"], + "created_at": r["created_at"].isoformat() if r["created_at"] else None, + } + for r in identities_rows + ], + } + + +@router.delete("/me") +async def auth_delete_me(request: Request): + """ + Удаление аккаунта Pleily-юзера. + Требуется Apple App Store (право на удаление внутри приложения). + + Требует Authorization: Bearer . + Удаляем users по telegram_id — FK CASCADE подчистит все связанные + таблицы (auth_identities, learning_sessions, user_learning_answers и т.д.). + """ + user_id, _username = await require_auth(request) + + pool = await get_pool() + async with pool.acquire() as conn: + # Проверяем существование + exists = await conn.fetchval( + "SELECT 1 FROM users WHERE telegram_id = $1", user_id + ) + if not exists: + raise HTTPException(404, "User not found") + + # Удаляем юзера — каскад подчистит auth_identities и остальное + await conn.execute( + "DELETE FROM users WHERE telegram_id = $1", user_id + ) + + logger.info(f"[app_auth] deleted Pleily user: telegram_id={user_id}") + return {"status": "ok", "user_id": user_id} \ No newline at end of file