From 7cd2882023553d4cc27db04e8d05a6b8653645a6 Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Fri, 04 Dec 2026 07:27:09 +0000
Subject: [PATCH] Add Telegram Mini App for admin panel

---
 web/templates/base.html |   21 +++++++
 cmds.py                 |   12 +++
 web/views.py            |   37 ++++++++++++
 main.py                 |   14 ++++
 web/auth.py             |   59 +++++++++++++++++++
 web/app.py              |    2 
 6 files changed, 142 insertions(+), 3 deletions(-)

diff --git a/cmds.py b/cmds.py
index 4a504fa..ae20b59 100644
--- a/cmds.py
+++ b/cmds.py
@@ -1,5 +1,6 @@
 from aiogram import F, types
 from aiogram.filters import Command, CommandObject
+from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
 
 import db
 import cfg
@@ -77,9 +78,18 @@
     if message.chat.type == "private" and message.from_user is not None:
         # Запоминаем, что боту можно писать в ЛС (для уведомлений тревоги).
         await db.add_dm(message.from_user.id, now_ts())
+        keyboard = None
+        if cfg.WEB_BASE_URL:
+            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
+                InlineKeyboardButton(
+                    text="Открыть панель",
+                    web_app=WebAppInfo(url=f"{cfg.WEB_BASE_URL}/miniapp"),
+                )
+            ]])
         await message.answer(
             "Привет! Я Amadeus. Теперь сюда будут приходить уведомления о тревоге. "
-            "Добавь меня в чат и выдай права администратора."
+            "Добавь меня в чат и выдай права администратора.",
+            reply_markup=keyboard,
         )
     else:
         await message.answer("Привет! Список команд: /help")
diff --git a/main.py b/main.py
index 85c5242..1461615 100644
--- a/main.py
+++ b/main.py
@@ -1,8 +1,10 @@
 import asyncio
 
+from aiogram.types import MenuButtonWebApp, WebAppInfo
+
 import db
 import mod
-from cfg import bot, dp, load_bot_username, logger
+from cfg import WEB_BASE_URL, bot, dp, load_bot_username, logger
 
 # Импорт модулей регистрирует обработчики на dp.
 # Порядок важен: команды (mod, alarm, report, stats) и общие команды (cmds)
@@ -22,6 +24,16 @@
 async def main() -> None:
     await db.init_db()
     await load_bot_username()
+    if WEB_BASE_URL:
+        try:
+            await bot.set_chat_menu_button(
+                menu_button=MenuButtonWebApp(
+                    text="Панель",
+                    web_app=WebAppInfo(url=f"{WEB_BASE_URL}/miniapp"),
+                )
+            )
+        except Exception as e:
+            logger.warning("Failed to set Mini App menu button: %s", e)
     # Снимаем наказания, срок которых истёк, пока бот был выключен.
     await mod._bg_tick()
 
diff --git a/web/app.py b/web/app.py
index a32bb58..9376357 100644
--- a/web/app.py
+++ b/web/app.py
@@ -13,8 +13,10 @@
     app.router.add_get("/", views.dashboard)
     app.router.add_get("/login", auth.login_page)
     app.router.add_get("/auth/telegram", auth.auth_telegram)
+    app.router.add_post("/auth/miniapp", auth.auth_miniapp)
     app.router.add_get("/logout", auth.logout)
     app.router.add_get("/chats", views.chats_page)
+    app.router.add_get("/miniapp", views.miniapp_page)
     app.router.add_get("/chats/{chat_id}", views.chat_page)
     app.router.add_get("/chats/{chat_id}/admin/{user_id}", views.admin_page)
     app.router.add_get("/chats/{chat_id}/messages", views.messages_page)
diff --git a/web/auth.py b/web/auth.py
index 2eb12b9..79577a4 100644
--- a/web/auth.py
+++ b/web/auth.py
@@ -1,5 +1,7 @@
 import hashlib
 import hmac
+import json
+import urllib.parse
 
 from aiohttp import web
 
@@ -42,6 +44,25 @@
     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
+
+
 @web.middleware
 async def session_mw(request, handler):
     request["user"] = None
@@ -50,7 +71,7 @@
         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") or request.path.startswith("/static")
     if request["user"] is None and not public:
         raise web.HTTPFound("/login")
     return await handler(request)
@@ -99,6 +120,42 @@
     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)
+    verified = verify_webapp_init_data(data.get("init_data", "") if isinstance(data, dict) else "")
+    if not verified:
+        return web.json_response({"ok": False, "msg": "Данные Telegram недействительны или устарели."}, status=401)
+    try:
+        tg_user = json.loads(verified["user"])
+        user_id = int(tg_user["id"])
+    except (KeyError, TypeError, ValueError, json.JSONDecodeError):
+        return web.json_response({"ok": False, "msg": "Не удалось определить пользователя Telegram."}, status=400)
+
+    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,
+    )
+    token = await db.create_sess(user_id, ts, SESS_TTL)
+    resp = web.json_response({"ok": True})
+    resp.set_cookie(
+        COOKIE,
+        token,
+        max_age=SESS_TTL,
+        httponly=True,
+        samesite="None",
+        secure=True,
+    )
+    return resp
+
+
 async def logout(request) -> web.Response:
     token = request.cookies.get(COOKIE)
     if token:
diff --git a/web/templates/base.html b/web/templates/base.html
index 312fae4..c43be4c 100644
--- a/web/templates/base.html
+++ b/web/templates/base.html
@@ -3,6 +3,7 @@
 <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+    <script src="https://telegram.org/js/telegram-web-app.js"></script>
     <title>{% block title %}Amadeus{% endblock %}</title>
     <script>
         // Применяем сохранённую тему до отрисовки, чтобы не мигало.
@@ -117,6 +118,26 @@
 </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) {}
+    })();
+
     // Переключатель тёмной/светлой темы.
     document.getElementById("theme-toggle").addEventListener("click", function () {
         const root = document.documentElement;
diff --git a/web/views.py b/web/views.py
index 644d0c8..27853b6 100644
--- a/web/views.py
+++ b/web/views.py
@@ -95,6 +95,43 @@
     return render(request, "chats.html", active="chats", chats=chats, cfgs=cfgs, alarms=alarms)
 
 
+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:
+            try:
+                tg_user = json.loads(verified["user"])
+                if int(tg_user["id"]) == user["user_id"]:
+                    chat = json.loads(verified.get("chat", "{}"))
+                    candidate = int(chat.get("id", 0)) if chat else 0
+                    if not candidate and verified.get("chat_instance"):
+                        instance = verified["chat_instance"]
+                        candidate = int(instance) if instance.lstrip("-").isdigit() else 0
+                    if candidate in available_ids:
+                        context = candidate
+            except (KeyError, TypeError, ValueError):
+                pass
+    if context is None:
+        context = request.query.get("chat_id", "")
+        try:
+            context = int(context)
+        except (TypeError, ValueError):
+            context = 0
+        if context not in available_ids:
+            context = 0
+    if context:
+        raise web.HTTPFound(f"/chats/{context}")
+    raise web.HTTPFound("/chats")
+
+
 async def chat_page(request) -> web.Response:
     user = await _user(request)
     chat_id = int(request.match_info["chat_id"])

--
Gitblit v1.9.3