From 809dbd0256d170a5c868f2bb112dbc92cc3f23d2 Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Fri, 04 Dec 2026 07:50:26 +0000
Subject: [PATCH] Fix Mini App login timeout and caching

---
 web/views.py                     |    4 +++-
 web/templates/miniapp_login.html |   21 +++++++++++++--------
 web/auth.py                      |   14 +++++++++++++-
 3 files changed, 29 insertions(+), 10 deletions(-)

diff --git a/web/auth.py b/web/auth.py
index 114c076..2541f89 100644
--- a/web/auth.py
+++ b/web/auth.py
@@ -103,7 +103,19 @@
     ) 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:
diff --git a/web/templates/miniapp_login.html b/web/templates/miniapp_login.html
index 69762cc..859e950 100644
--- a/web/templates/miniapp_login.html
+++ b/web/templates/miniapp_login.html
@@ -4,7 +4,7 @@
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
     <title>Вход — Amadeus</title>
-    <script src="https://telegram.org/js/telegram-web-app.js"></script>
+    <script src="https://telegram.org/js/telegram-web-app.js?v=8"></script>
     <script src="https://cdn.tailwindcss.com"></script>
     <link rel="stylesheet" href="/static/style.css">
 </head>
@@ -20,27 +20,30 @@
             const status = document.getElementById("status");
             const retry = document.getElementById("retry");
             let started = false;
+            let finished = false;
+
+            setTimeout(function () {
+                if (!finished) {
+                    showError("Вход не завершился за 15 секунд. Нажмите «Попробовать ещё раз» или закройте и снова откройте Mini App.");
+                }
+            }, 15000);
 
             function showError(message) {
                 status.textContent = message;
                 retry.classList.remove("hidden");
             }
 
-            setTimeout(function () {
-                if (!started && status.textContent.indexOf("Проверяем вход") === 0) {
-                    showError("Telegram Web App не загрузился. Проверьте доступ к telegram.org и обновите приложение.");
-                }
-            }, 5000);
-
             async function authenticate() {
                 if (started) return;
+                started = true;
                 const tg = window.Telegram && window.Telegram.WebApp;
                 if (!tg || !tg.initData) {
+                    started = false;
+                    finished = true;
                     showError("Telegram не передал данные Mini App. Закройте окно и откройте панель из меню бота в Telegram.");
                     return;
                 }
 
-                started = true;
                 status.textContent = "Выполняем безопасный вход…";
                 retry.classList.add("hidden");
                 try {
@@ -64,9 +67,11 @@
                     }
                     const result = await response.json();
                     if (!response.ok || !result.ok) throw new Error(result.msg || "Сервер отклонил данные Telegram.");
+                    finished = true;
                     location.replace(destination);
                 } catch (error) {
                     started = false;
+                    finished = true;
                     showError(error.name === "AbortError"
                         ? "Сервер не ответил за 12 секунд. Проверьте соединение и попробуйте ещё раз."
                         : (error.message || "Не удалось выполнить вход. Проверьте соединение."));
diff --git a/web/views.py b/web/views.py
index 67b338c..dfc0e6c 100644
--- a/web/views.py
+++ b/web/views.py
@@ -126,7 +126,9 @@
     """Стартовая HTML-страница: получает initData через Telegram WebApp JS API."""
     if request["user"] is not None:
         raise web.HTTPFound("/miniapp")
-    return render(request, "miniapp_login.html")
+    response = render(request, "miniapp_login.html")
+    response.headers["X-Amadeus-MiniApp-Version"] = "5387fa6"
+    return response
 
 
 async def chat_page(request) -> web.Response:

--
Gitblit v1.9.3