From efbad4ca31219bd7495adf95cee7b4127cad06c8 Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Fri, 04 Dec 2026 07:44:32 +0000
Subject: [PATCH] Fix Telegram Mini App authentication flow

---
 web/views.py |   52 +++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 49 insertions(+), 3 deletions(-)

diff --git a/web/views.py b/web/views.py
index 936167f..67b338c 100644
--- a/web/views.py
+++ b/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,11 +92,41 @@
 
 
 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()}
     return render(request, "chats.html", active="chats", chats=chats, cfgs=cfgs, alarms=alarms)
+
+
+async def miniapp_page(request) -> web.Response:
+    """Выбирает стартовый экран Mini App по chat_id из Telegram launch URL."""
+    if request["user"] is None:
+        raise web.HTTPFound("/miniapp/login")
+
+    user_id = request["user"]["user_id"]
+    chats = await allowed_chats(user_id)
+    available_ids = {c["chat_id"] for c in chats}
+    try:
+        context = int(request.query.get("chat_id", "") or 0)
+    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 miniapp_login_page(request) -> web.Response:
+    """Стартовая HTML-страница: получает initData через Telegram WebApp JS API."""
+    if request["user"] is not None:
+        raise web.HTTPFound("/miniapp")
+    return render(request, "miniapp_login.html")
 
 
 async def chat_page(request) -> web.Response:
@@ -247,10 +281,20 @@
         return web.json_response({"ok": False, "msg": "Пустое сообщение."}, status=400)
     name = user.get("first_name") or str(user["user_id"])
     ts = now_ts()
+    reply_to_name = ""
+    reply_to_text = ""
+    if reply_id:
+        rm = await db.find_msg_by_tg(chat_id, reply_id)
+        if rm:
+            reply_to_name = rm["name"] or ""
+            reply_to_text = (rm["text"] or "")[:80]
     tg_id = await _deliver(chat_id, name, text, reply_id)
     if tg_id < 0:
         return web.json_response({"ok": False, "msg": "Не удалось отправить. Проверьте права бота."}, status=502)
-    mid = await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, ts, tg_id)
+    mid = await db.add_msg(
+        chat_id, user["user_id"], f"Amadeus / {name}", text, ts, tg_id,
+        reply_to_tg=reply_id, reply_to_name=reply_to_name, reply_to_text=reply_to_text,
+    )
     await db.add_log(chat_id, user["user_id"], 0, "say", text[:200], ts)
     return web.json_response({
         "ok": True,
@@ -258,6 +302,8 @@
             "id": mid, "chat_id": chat_id, "user_id": user["user_id"],
             "name": f"Amadeus / {name}", "text": text, "created_at": ts,
             "tg_msg_id": tg_id, "time": fmt_dt(ts),
+            "media_type": "", "media_file_id": "",
+            "reply_to_tg": reply_id, "reply_to_name": reply_to_name, "reply_to_text": reply_to_text,
         },
     })
 

--
Gitblit v1.9.3