Files
filwordspl-backend/routers/app_auth.py
T
Drobysh 84927b063f feat: XP foundation + waves + featured game + profile + leaderboard by total_xp
- services/xp.py: award_xp, level_for, RANKS (48), featured_game
- services/waves.py: wave_plan, grid_size_for, wave_medal
- routers/featured.py: GET /featured (игра дня ×1.5)
- routers/users.py: POST /set-nickname, POST /set-avatar
- routers/app_auth.py: /auth/me с XP-полями (level, rank_key, rank_name, xp)
- routers/game.py: award_xp + 3 штрафа + POST /game/next (волны)
- routers/wordquiz.py: award_xp + серии в choose_progress
- routers/bubblewords.py: award_xp + 4 штрафа
- routers/sentences.py: award_xp по длине предложения
- routers/leaderboard.py: сортировка по total_xp, XP-поля в ответе
- database.py: миграции user_profile, xp_log, choose_progress, user_seen_levels, user_game_progress, wave_results, bubble_levels, user_word_stats
- main.py: подключение routers/featured

Проверено:
- /auth/me отдаёт level=1, rank_00, xp_in_level
- /featured отдаёт wordsearch + seconds_left
- /game/complete-level начисляет XP через award_xp
- xp_log, user_profile заполняются
- /game/next выдаёт уровень по волнам
- /leaderboard сортирует по total_xp
2026-10-09 08:12:19 +00:00

287 lines
11 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.
"""
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 — первая версия.
🔧 ФИКС (07.10.2026): device_id_in_users —
теперь device_id пишется и в users.device_id, и в auth_identities.
Это нужно для SQL-запросов по device_id (админка, миграции).
🔧 НОВОЕ (08.10.2026): auth_me_xp_fields —
в /auth/me добавлены XP-поля: level, rank_key, rank_name,
xp_in_level, xp_needed, total_xp, weekly_xp, weekly_rank.
"""
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"]
# 🔧 ФИКС (07.10.2026): device_id_in_users —
# раньше device_id сохранялся только в auth_identities,
# а в users.device_id был NULL. Теперь — в обоих местах.
# Это нужно для SQL-запросов по device_id (админка, миграции).
await conn.execute("""
INSERT INTO users (telegram_id, username, source, device_id)
VALUES ($1, $2, 'app', $3)
""", uid, f"app_user_{abs(uid)}", device_id)
# Создаём 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):
"""
Текущий юзер + XP-поля.
🔧 НОВОЕ (08.10.2026): добавлены level, rank_key, rank_name,
xp_in_level, xp_needed, total_xp, weekly_xp.
"""
telegram_id, _ = await require_auth(request)
pool = await get_pool()
async with pool.acquire() as conn:
user = await conn.fetchrow(
"""
SELECT telegram_id, username, app_language, current_level,
source, device_id, apple_id, created_at
FROM users WHERE telegram_id = $1
""",
telegram_id,
)
if not user:
raise HTTPException(401, "User not found")
profile = await conn.fetchrow(
"""
SELECT nickname, avatar_id, total_xp, weekly_xp, week_started_at
FROM user_profile WHERE user_id = $1
""",
telegram_id,
)
# Weekly rank
weekly_rank = await conn.fetchval(
"""
SELECT COUNT(*) + 1
FROM user_profile
WHERE weekly_xp > COALESCE((
SELECT weekly_xp FROM user_profile WHERE user_id = $1
), 0)
""",
telegram_id,
)
# Считаем уровень
from services.xp import level_for, rank_for
total_xp = int(profile["total_xp"]) if profile else 0
weekly_xp = int(profile["weekly_xp"]) if profile else 0
level, xp_in_level, xp_needed, rank_key = level_for(total_xp)
lang = (user["app_language"] or "ru").lower()
if lang not in ("pl", "ru", "uk", "en"):
lang = "ru"
return {
"user_id": user["telegram_id"],
"username": user["username"],
"nickname": profile["nickname"] if profile else None,
"avatar_id": int(profile["avatar_id"]) if profile and profile["avatar_id"] is not None else 0,
"app_language": user["app_language"],
"current_level": user["current_level"],
"source": user["source"],
"device_id": str(user["device_id"]) if user["device_id"] else None,
"apple_id": user["apple_id"],
"created_at": user["created_at"].isoformat() if user["created_at"] else None,
# --- XP ---
"total_xp": total_xp,
"weekly_xp": weekly_xp,
"level": level,
"rank_key": rank_key,
"rank_name": rank_for(level, lang),
"xp_in_level": xp_in_level,
"xp_needed": xp_needed,
"weekly_rank": int(weekly_rank) if weekly_rank else 0,
}
@router.delete("/me")
async def auth_delete_me(request: Request):
"""
Удаление аккаунта Pleily-юзера.
Требуется Apple App Store (право на удаление внутри приложения).
Требует Authorization: Bearer <JWT>.
Удаляем 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}