Бот для капчи в чатах
Roman Sergienko
2026-10-10 c3f15480f581df8799eeead71987956db11e85b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import hashlib
import hmac
 
from aiohttp import web
 
import db
from cfg import BOT_USERNAME, OWNER_ID, WEB_ADMINS, WEB_BASE_URL, bot
from util import now_ts
from web.render import render
 
SESS_TTL = 7 * 86400
COOKIE = "amd_sess"
 
 
def base_url(request) -> str:
    if WEB_BASE_URL:
        return WEB_BASE_URL
    proto = request.headers.get("X-Forwarded-Proto", request.scheme)
    host = request.headers.get("X-Forwarded-Host", request.host)
    return f"{proto}://{host}"
 
 
def is_staff(user_id: int) -> bool:
    return user_id == OWNER_ID or user_id in WEB_ADMINS
 
 
def verify_login(data: dict) -> bool:
    # Проверка подписи Telegram Login Widget: HMAC-SHA256 на секрете из токена бота.
    check = data.get("hash")
    if not check:
        return False
    pairs = sorted(f"{k}={v}" for k, v in data.items() if k != "hash")
    secret = hashlib.sha256(bot.token.encode()).digest()
    calc = hmac.new(secret, "\n".join(pairs).encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(calc, check):
        return False
    try:
        auth_date = int(data.get("auth_date", "0"))
    except ValueError:
        return False
    return now_ts() - auth_date <= 86400
 
 
@web.middleware
async def session_mw(request, handler):
    request["user"] = None
    token = request.cookies.get(COOKIE)
    if token:
        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")
    if request["user"] is None and not public:
        raise web.HTTPFound("/login")
    return await handler(request)
 
 
async def login_page(request) -> web.Response:
    return render(
        request,
        "login.html",
        bot_username=BOT_USERNAME,
        auth_url=base_url(request) + "/auth/telegram",
    )
 
 
async def auth_telegram(request) -> web.Response:
    q = dict(request.query)
    if not verify_login(q):
        raise web.HTTPFound("/login?err=1")
    try:
        user_id = int(q["id"])
    except (KeyError, ValueError):
        raise web.HTTPFound("/login?err=1")
 
    ts = now_ts()
    await db.upsert_web_user(
        user_id,
        q.get("first_name", ""),
        q.get("last_name", ""),
        q.get("username", ""),
        q.get("photo_url", ""),
        ts,
    )
    token = await db.create_sess(user_id, ts, SESS_TTL)
    resp = web.HTTPFound("/")
    resp.set_cookie(
        COOKIE,
        token,
        max_age=SESS_TTL,
        httponly=True,
        samesite="Lax",
        secure=base_url(request).startswith("https"),
    )
    return resp
 
 
async def logout(request) -> web.Response:
    token = request.cookies.get(COOKIE)
    if token:
        await db.del_sess(token)
    resp = web.HTTPFound("/login")
    resp.del_cookie(COOKIE)
    return resp