Бот для капчи в чатах
Roman Sergienko
12 hours ago 809dbd0256d170a5c868f2bb112dbc92cc3f23d2
web/auth.py
@@ -1,5 +1,7 @@
import hashlib
import hmac
import json
import urllib.parse
from aiohttp import web
@@ -42,6 +44,48 @@
    return now_ts() - auth_date <= 86400
def verify_webapp_init_data(init_data: str) -> dict | None:
    """Проверяет подпись Telegram Mini App initData и возвращает разобранные поля."""
    try:
        pairs = dict(urllib.parse.parse_qsl(init_data, keep_blank_values=True))
        received_hash = pairs.pop("hash", "")
        auth_date = int(pairs.get("auth_date", "0"))
    except (TypeError, ValueError):
        return None
    if not received_hash or now_ts() - auth_date > 86400 or auth_date > now_ts() + 30:
        return None
    data_check_string = "\n".join(f"{key}={value}" for key, value in sorted(pairs.items()))
    secret = hmac.new(b"WebAppData", bot.token.encode(), hashlib.sha256).digest()
    calc = hmac.new(secret, data_check_string.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(calc, received_hash):
        return None
    return pairs
async def create_miniapp_session(init_data: str) -> str | None:
    """Проверяет Telegram initData и возвращает токен веб-сессии."""
    verified = verify_webapp_init_data(init_data)
    if not verified:
        return None
    try:
        tg_user = json.loads(verified["user"])
        user_id = int(tg_user["id"])
    except (KeyError, TypeError, ValueError, json.JSONDecodeError):
        return None
    ts = now_ts()
    await db.upsert_web_user(
        user_id,
        tg_user.get("first_name", ""),
        tg_user.get("last_name", ""),
        tg_user.get("username", ""),
        tg_user.get("photo_url", ""),
        ts,
    )
    return await db.create_sess(user_id, ts, SESS_TTL)
@web.middleware
async def session_mw(request, handler):
    request["user"] = None
@@ -50,10 +94,28 @@
        sess = await db.get_sess(token, now_ts())
        if sess:
            request["user"] = await db.get_web_user(sess["user_id"]) or {"user_id": sess["user_id"], "first_name": ""}
    public = request.path in ("/login", "/auth/telegram") or request.path.startswith("/static")
    public = request.path in (
        "/login",
        "/auth/telegram",
        "/auth/miniapp",
        "/miniapp",
        "/miniapp/login",
    ) or request.path.startswith("/static")
    if request["user"] is None and not public:
        raise web.HTTPFound("/login")
    return await handler(request)
    try:
        response = await handler(request)
    except web.HTTPException as response:
        if request.path.startswith("/miniapp") or request.path == "/auth/miniapp":
            response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
            response.headers["Pragma"] = "no-cache"
        raise
    if request.path.startswith("/miniapp") or request.path == "/auth/miniapp":
        response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
        response.headers["Pragma"] = "no-cache"
    if request.path.startswith("/static/"):
        response.headers["Cache-Control"] = "no-cache, must-revalidate, max-age=0"
    return response
async def login_page(request) -> web.Response:
@@ -99,6 +161,26 @@
    return resp
async def auth_miniapp(request) -> web.Response:
    try:
        data = await request.json()
    except (ValueError, web.HTTPException):
        return web.json_response({"ok": False, "msg": "Некорректный запрос."}, status=400)
    token = await create_miniapp_session(data.get("init_data", "") if isinstance(data, dict) else "")
    if not token:
        return web.json_response({"ok": False, "msg": "Данные Telegram недействительны или устарели."}, status=401)
    resp = web.json_response({"ok": True})
    resp.set_cookie(
        COOKIE,
        token,
        max_age=SESS_TTL,
        httponly=True,
        samesite="Lax",
        secure=base_url(request).startswith("https"),
    )
    return resp
async def logout(request) -> web.Response:
    token = request.cookies.get(COOKIE)
    if token: