Бот для капчи в чатах
Roman Sergienko
12 hours ago 9318fc842964d6de64b778cd5c617c6859ca56a2
Auto-authenticate Telegram Mini App
3 files modified
85 ■■■■■ changed files
web/auth.py 6 ●●●●● patch | view | raw | blame | history
web/templates/base.html 21 ●●●●● patch | view | raw | blame | history
web/views.py 58 ●●●●● patch | view | raw | blame | history
web/auth.py
@@ -71,7 +71,11 @@
        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", "/auth/miniapp") or request.path.startswith("/static")
    public = request.path in (
        "/login",
        "/auth/telegram",
        "/auth/miniapp",
    ) or request.path.startswith("/static")
    if request["user"] is None and not public:
        raise web.HTTPFound("/login")
    return await handler(request)
web/templates/base.html
@@ -118,25 +118,8 @@
</nav>
<script>
    // Mini App передаёт подписанные Telegram данные; сервер проверяет подпись и создаёт
    // ту же защищённую сессию, что используется обычной веб-панелью.
    (async function () {
        const tg = window.Telegram && window.Telegram.WebApp;
        if (!tg || !tg.initData || sessionStorage.getItem("amd-miniapp-auth")) return;
        try {
            const response = await fetch("/auth/miniapp", {
                method: "POST",
                credentials: "same-origin",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ init_data: tg.initData })
            });
            if (response.ok) {
                sessionStorage.setItem("amd-miniapp-auth", "1");
                tg.ready();
                location.reload();
            }
        } catch (e) {}
    })();
    // Авторизация создаётся сервером до отображения панели по подписанным initData.
    if (window.Telegram && window.Telegram.WebApp) window.Telegram.WebApp.ready();
    // Переключатель тёмной/светлой темы.
    document.getElementById("theme-toggle").addEventListener("click", function () {
web/views.py
@@ -63,7 +63,11 @@
async def dashboard(request) -> web.Response:
    user = await _user(request)
    user = request["user"]
    if user is None:
        if request.headers.get("X-Telegram-Web-App-Platform"):
            raise web.HTTPFound("/miniapp")
        raise web.HTTPFound("/login")
    chats = await allowed_chats(user["user_id"])
    ids = {c["chat_id"] for c in chats}
    names = {c["chat_id"]: c["title"] for c in chats}
@@ -88,7 +92,11 @@
async def chats_page(request) -> web.Response:
    user = await _user(request)
    user = request["user"]
    if user is None:
        if request.headers.get("X-Telegram-Web-App-Platform"):
            raise web.HTTPFound("/miniapp")
        raise web.HTTPFound("/login")
    chats = await allowed_chats(user["user_id"])
    cfgs = {c["chat_id"]: await db.get_chat_cfg(c["chat_id"]) for c in chats}
    alarms = {r["chat_id"]: r for r in await db.list_alarm_chats()}
@@ -97,19 +105,47 @@
async def miniapp_page(request) -> web.Response:
    """Выбирает стартовый экран Mini App по проверенному initData Telegram."""
    user = await _user(request)
    chats = await allowed_chats(user["user_id"])
    available_ids = {c["chat_id"] for c in chats}
    init_data = request.query.get("tgWebAppData", "")
    context = None
    if init_data:
        from web.auth import verify_webapp_init_data
        verified = verify_webapp_init_data(init_data)
        if verified:
    verified = verify_webapp_init_data(init_data) if init_data else None
    if not verified:
        raise web.HTTPUnauthorized(text="Откройте панель через Telegram.")
            try:
                tg_user = json.loads(verified["user"])
                if int(tg_user["id"]) == user["user_id"]:
        user_id = int(tg_user["id"])
    except (KeyError, TypeError, ValueError):
        raise web.HTTPUnauthorized(text="Не удалось проверить пользователя Telegram.")
    if request["user"] is None or request["user"]["user_id"] != user_id:
        # Создаём веб-сессию на основании только что проверенного initData.
        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,
        )
        from web.auth import COOKIE, SESS_TTL
        token = await db.create_sess(user_id, ts, SESS_TTL)
        response = web.HTTPFound(request.path_qs)
        response.set_cookie(
            COOKIE,
            token,
            max_age=SESS_TTL,
            httponly=True,
            samesite="None",
            secure=True,
        )
        raise response
    chats = await allowed_chats(user_id)
    available_ids = {c["chat_id"] for c in chats}
    context = None
    try:
                    chat = json.loads(verified.get("chat", "{}"))
                    candidate = int(chat.get("id", 0)) if chat else 0
                    if not candidate and verified.get("chat_instance"):
@@ -117,7 +153,7 @@
                        candidate = int(instance) if instance.lstrip("-").isdigit() else 0
                    if candidate in available_ids:
                        context = candidate
            except (KeyError, TypeError, ValueError):
    except (TypeError, ValueError):
                pass
    if context is None:
        context = request.query.get("chat_id", "")