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/static/miniapp-login.js | 33 +++++++++++
web/views.py | 69 +++++------------------
web/templates/miniapp_login.html | 20 ++++++
web/auth.py | 49 +++++++++------
web/app.py | 1
5 files changed, 98 insertions(+), 74 deletions(-)
diff --git a/web/app.py b/web/app.py
index 9376357..0729256 100644
--- a/web/app.py
+++ b/web/app.py
@@ -17,6 +17,7 @@
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("/miniapp/login", views.miniapp_login_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 3ef6cbc..114c076 100644
--- a/web/auth.py
+++ b/web/auth.py
@@ -63,6 +63,29 @@
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
@@ -75,6 +98,8 @@
"/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")
@@ -129,33 +154,17 @@
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:
+ 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)
- 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,
+ samesite="Lax",
+ secure=base_url(request).startswith("https"),
)
return resp
diff --git a/web/static/miniapp-login.js b/web/static/miniapp-login.js
new file mode 100644
index 0000000..5f650e0
--- /dev/null
+++ b/web/static/miniapp-login.js
@@ -0,0 +1,33 @@
+const tg = window.Telegram && window.Telegram.WebApp;
+const status = document.getElementById("status");
+const retry = document.getElementById("retry");
+
+async function authenticate() {
+ if (!tg || !tg.initData) {
+ status.textContent = "Откройте панель кнопкой Mini App в Telegram.";
+ retry.classList.remove("hidden");
+ return;
+ }
+
+ tg.ready();
+ try {
+ const params = new URLSearchParams(location.search);
+ params.delete("auth");
+ const destination = "/miniapp" + (params.size ? "?" + params.toString() : "");
+ const response = await fetch("/auth/miniapp", {
+ method: "POST",
+ credentials: "same-origin",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ init_data: tg.initData })
+ });
+ const result = await response.json();
+ if (!response.ok || !result.ok) throw new Error(result.msg || "Не удалось войти.");
+ location.replace(destination);
+ } catch (error) {
+ status.textContent = error.message || "Не удалось выполнить вход. Попробуйте ещё раз.";
+ retry.classList.remove("hidden");
+ }
+}
+
+retry.addEventListener("click", authenticate);
+authenticate();
diff --git a/web/templates/miniapp_login.html b/web/templates/miniapp_login.html
new file mode 100644
index 0000000..c33fb18
--- /dev/null
+++ b/web/templates/miniapp_login.html
@@ -0,0 +1,20 @@
+<!doctype html>
+<html lang="ru" class="dark">
+<head>
+ <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="/static/miniapp-login.js" defer></script>
+ <script src="https://cdn.tailwindcss.com"></script>
+ <link rel="stylesheet" href="/static/style.css">
+</head>
+<body class="min-h-screen flex items-center justify-center bg-gray-950 p-6 font-sans text-gray-100">
+ <main class="w-full max-w-sm rounded-2xl border border-gray-800 bg-gray-900 p-6 text-center shadow-xl">
+ <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-indigo-600 text-xl font-bold">A</div>
+ <h1 class="mt-4 text-xl font-semibold">Панель Amadeus</h1>
+ <p id="status" class="mt-2 text-sm text-gray-400">Проверяем вход через Telegram…</p>
+ <button id="retry" class="mt-5 hidden rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium hover:bg-indigo-500">Попробовать ещё раз</button>
+ </main>
+</body>
+</html>
diff --git a/web/views.py b/web/views.py
index 4ba0dc1..67b338c 100644
--- a/web/views.py
+++ b/web/views.py
@@ -104,70 +104,31 @@
async def miniapp_page(request) -> web.Response:
- """Выбирает стартовый экран Mini App по проверенному initData Telegram."""
- init_data = request.query.get("tgWebAppData", "")
- from web.auth import verify_webapp_init_data
+ """Выбирает стартовый экран Mini App по chat_id из Telegram launch URL."""
+ if request["user"] is None:
+ raise web.HTTPFound("/miniapp/login")
- 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"])
- 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
-
+ user_id = request["user"]["user_id"]
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"):
- instance = verified["chat_instance"]
- candidate = int(instance) if instance.lstrip("-").isdigit() else 0
- if candidate in available_ids:
- context = candidate
+ context = int(request.query.get("chat_id", "") or 0)
except (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
+ 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:
user = await _user(request)
chat_id = int(request.match_info["chat_id"])
--
Gitblit v1.9.3