From 5387fa65bbf77233fc2f42d0a986ba275d067d08 Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Fri, 04 Dec 2026 07:45:57 +0000
Subject: [PATCH] Show Mini App authentication errors
---
web/views.py | 69 +++++++---------------------------
1 files changed, 15 insertions(+), 54 deletions(-)
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