fix(register): вернуть ОБЯЗАТЕЛЬНОЕ поле Telegram (снёс лишнее — просили убрать только телефон)
Ошибка прошлой правки: убрал всё поле контакта, а Юрий просил убрать ТОЛЬКО телефон. Возвращаю поле Telegram, теперь ОБЯЗАТЕЛЬНОЕ: фронт+бэк требуют непустой telegram (400 без него), уходит оператору в TG-алерт, в БД НЕ хранится. bump 2026-07-23h. +2 теста (telegram обязателен / в алерте не в БД), 4 существующих тела дополнены telegram. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -207,7 +207,7 @@ MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-07-23g"
|
||||
APP_VERSION = "2026-07-23h"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
@@ -641,6 +641,13 @@ async def register(request: Request, background: BackgroundTasks):
|
||||
client_ip, 400)
|
||||
raise HTTPException(400, "Требуется согласие на обработку персональных данных.")
|
||||
|
||||
# Telegram — ОБЯЗАТЕЛЬНОЕ поле (решение Юрия 2026-07-23): уходит оператору в TG-алерт, в БД
|
||||
# НЕ хранится. Схлопываем whitespace (в т.ч. \r\n — защита от дописывания строк в алерт), режем.
|
||||
telegram = " ".join(str(body.get("telegram") or "").split())[:150]
|
||||
if not telegram:
|
||||
log_action(email, "register_fail", "POST", "/api/register", "no-telegram", client_ip, 400)
|
||||
raise HTTPException(400, "Укажите ваш Telegram — это обязательное поле.")
|
||||
|
||||
# Анти-бот (Ф4 публичного запуска): порядок дешёвое→дорогое, всё фичефлагами.
|
||||
import antibot
|
||||
if not antibot.register_ip_allowed(client_ip or ""):
|
||||
@@ -669,7 +676,7 @@ async def register(request: Request, background: BackgroundTasks):
|
||||
import alerts
|
||||
background.add_task(
|
||||
alerts.send_tg,
|
||||
f"🆕 smeta-web: новая регистрация — {email} "
|
||||
f"🆕 smeta-web: новая регистрация — {email}, Telegram: {telegram} "
|
||||
f"(IP {client_ip or '—'}, ожидает подтверждения email)")
|
||||
|
||||
# Send verification code via email
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
[
|
||||
{
|
||||
"version": "2026-07-23h",
|
||||
"date": "2026-07-23",
|
||||
"changes": [
|
||||
"При регистрации — обязательное поле Telegram (для связи и поддержки)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026-07-23g",
|
||||
"date": "2026-07-23",
|
||||
@@ -28,12 +35,5 @@
|
||||
"changes": [
|
||||
"Ассистент отвечает индексами пересчёта из писем Минстроя — со ссылкой на номер письма и страницу"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026-07-23c",
|
||||
"date": "2026-07-23",
|
||||
"changes": [
|
||||
"Кнопка «Админ» открывается в текущем окне, а не в новой вкладке"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -58,6 +58,8 @@ document.addEventListener('DOMContentLoaded',applyThemeIcon);
|
||||
<input type="password" id="reg-pass" placeholder="Минимум 6 символов">
|
||||
<label>Повторите пароль</label>
|
||||
<input type="password" id="reg-pass2" placeholder="Повторите пароль">
|
||||
<label>Telegram — обязательно (для связи и поддержки)</label>
|
||||
<input type="text" id="reg-telegram" placeholder="@username" maxlength="150">
|
||||
<div id="captcha-container" style="margin:.6rem 0"></div>
|
||||
<label style="display:flex;gap:.5rem;align-items:flex-start;font-weight:400;font-size:.82rem;cursor:pointer;margin-bottom:1rem">
|
||||
<input type="checkbox" id="reg-consent" style="width:auto;margin:2px 0 0">
|
||||
@@ -123,6 +125,8 @@ async function doRegister() {
|
||||
if (!email || !pass) { err.textContent = 'Заполните все поля'; err.style.display = 'block'; return; }
|
||||
if (pass !== pass2) { err.textContent = 'Пароли не совпадают'; err.style.display = 'block'; return; }
|
||||
if (pass.length < 6) { err.textContent = 'Пароль минимум 6 символов'; err.style.display = 'block'; return; }
|
||||
const tg = document.getElementById('reg-telegram').value.trim();
|
||||
if (!tg) { err.textContent = 'Укажите ваш Telegram (обязательно)'; err.style.display = 'block'; return; }
|
||||
// Инвайт НЕ обязателен: открытая регистрация. Если ссылка-приглашение есть в URL —
|
||||
// уходит в запрос (реферальный бонус); нет — регистрируемся без неё.
|
||||
if (!document.getElementById('reg-consent').checked) {
|
||||
@@ -135,7 +139,7 @@ async function doRegister() {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({email, password: pass, invite: inviteToken,
|
||||
consent: true,
|
||||
telegram: tg, consent: true,
|
||||
captcha_token: (captchaWidgetId !== null && window.smartCaptcha)
|
||||
? window.smartCaptcha.getResponse(captchaWidgetId) : ''}),
|
||||
});
|
||||
|
||||
@@ -268,7 +268,7 @@ def test_verify_endpoint_grants_bonus_and_audits(client_env, monkeypatch):
|
||||
db.create_invite("http-tok", "hinv@x.ru")
|
||||
r = client.post("/api/register", json={
|
||||
"email": "hreg@x.ru", "password": "secret1", "invite": "http-tok",
|
||||
"consent": True})
|
||||
"telegram": "@hreg", "consent": True})
|
||||
assert r.status_code == 200
|
||||
with sqlite3.connect(os.environ["DB_PATH"]) as c:
|
||||
code = c.execute("SELECT verify_code FROM users WHERE email='hreg@x.ru'").fetchone()[0]
|
||||
|
||||
@@ -111,7 +111,7 @@ def client_env(tmp_path, monkeypatch):
|
||||
def test_register_disposable_400(client_env, monkeypatch):
|
||||
db, auth, client, invite = client_env
|
||||
r = client.post("/api/register", json={
|
||||
"email": "bot@mailinator.com", "password": "secret1", "invite": invite, "consent": True})
|
||||
"email": "bot@mailinator.com", "password": "secret1", "invite": invite, "telegram": "@bot", "consent": True})
|
||||
assert r.status_code == 400
|
||||
assert "почт" in r.json()["detail"].lower() or "email" in r.json()["detail"].lower()
|
||||
assert db.get_user_by_email("bot@mailinator.com") is None
|
||||
@@ -122,7 +122,7 @@ def test_register_normal_ok_without_captcha_keys(client_env, monkeypatch):
|
||||
db, auth, client, invite = client_env
|
||||
monkeypatch.setattr("email_service.send_verification_code", lambda e, c: True)
|
||||
r = client.post("/api/register", json={
|
||||
"email": "human@yandex.ru", "password": "secret1", "invite": invite, "consent": True})
|
||||
"email": "human@yandex.ru", "password": "secret1", "invite": invite, "telegram": "@human", "consent": True})
|
||||
assert r.status_code == 200
|
||||
assert db.get_user_by_email("human@yandex.ru") is not None
|
||||
|
||||
@@ -137,7 +137,7 @@ def test_register_sends_tg_notification(client_env, monkeypatch):
|
||||
import alerts
|
||||
monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True)
|
||||
r = client.post("/api/register", json={
|
||||
"email": "newbie@yandex.ru", "password": "secret1", "invite": invite, "consent": True})
|
||||
"email": "newbie@yandex.ru", "password": "secret1", "invite": invite, "telegram": "@newbie", "consent": True})
|
||||
assert r.status_code == 200
|
||||
assert len(sent) == 1 # ровно один алерт на регистрацию
|
||||
assert "newbie@yandex.ru" in sent[0] # с email нового юзера
|
||||
@@ -150,7 +150,7 @@ def test_register_normalizes_email_case_in_audit(client_env, monkeypatch):
|
||||
db, auth, client, invite = client_env
|
||||
monkeypatch.setattr("email_service.send_verification_code", lambda e, c: True)
|
||||
r = client.post("/api/register", json={
|
||||
"email": "Shelemetevay@MAIL.ru", "password": "secret1", "invite": invite, "consent": True})
|
||||
"email": "Shelemetevay@MAIL.ru", "password": "secret1", "invite": invite, "telegram": "@shel", "consent": True})
|
||||
assert r.status_code == 200
|
||||
users = {row["username"] for row in db.get_audit_log(action="register") if row.get("username")}
|
||||
assert "shelemetevay@mail.ru" in users
|
||||
@@ -178,6 +178,6 @@ def test_failed_register_no_tg_notification(client_env, monkeypatch):
|
||||
import alerts
|
||||
monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True)
|
||||
r = client.post("/api/register", json={
|
||||
"email": "bot@mailinator.com", "password": "secret1", "invite": invite, "consent": True})
|
||||
"email": "bot@mailinator.com", "password": "secret1", "invite": invite, "telegram": "@bot", "consent": True})
|
||||
assert r.status_code == 400
|
||||
assert sent == []
|
||||
|
||||
@@ -55,7 +55,7 @@ def env(tmp_path, monkeypatch):
|
||||
|
||||
def _reg_body(invite, **over):
|
||||
body = {"email": "human@yandex.ru", "password": "secret1",
|
||||
"invite": invite, "consent": True}
|
||||
"invite": invite, "telegram": "@human", "consent": True}
|
||||
body.update(over)
|
||||
return body
|
||||
|
||||
@@ -119,17 +119,28 @@ def test_register_bad_invite_rejected(env):
|
||||
assert db.get_user_by_email("human@yandex.ru") is None
|
||||
|
||||
|
||||
# --- 2. Контакт-поле убрано (решение Юрия: по телефону код не получить) ---
|
||||
# --- 2. Telegram — ОБЯЗАТЕЛЬНОЕ поле (в TG-алерт оператору, НЕ в БД) ---
|
||||
|
||||
def test_no_contact_field_alert_email_only(env):
|
||||
"""Поле контакта убрано; алерт оператору — только email, без «контакт=».
|
||||
Mutation: вернуть contact в текст алерта → появится «контакт» → упадёт."""
|
||||
def test_telegram_required_400(env):
|
||||
"""Пустой telegram → 400 (обязательное поле), аккаунт НЕ создан, алерта нет.
|
||||
Mutation: убрать проверку telegram в хендлере → 200 → упадёт."""
|
||||
db, auth, client, invite, sent, _ = env
|
||||
r = client.post("/api/register", json=_reg_body(invite))
|
||||
r = client.post("/api/register", json=_reg_body(invite, telegram=""))
|
||||
assert r.status_code == 400
|
||||
assert "telegram" in r.json()["detail"].lower()
|
||||
assert db.get_user_by_email("human@yandex.ru") is None
|
||||
assert sent == []
|
||||
|
||||
|
||||
def test_telegram_in_alert_not_in_db(env):
|
||||
"""Telegram из формы → в тексте send_tg оператору, но НИ В ОДНОМ файле БД (не хранится).
|
||||
Mutation: не передать telegram в алерт → упадёт; записать в users/audit → упадёт скан БД."""
|
||||
db, auth, client, invite, sent, db_path = env
|
||||
r = client.post("/api/register", json=_reg_body(invite, telegram="@durovtest"))
|
||||
assert r.status_code == 200
|
||||
assert len(sent) == 1
|
||||
assert "human@yandex.ru" in sent[0]
|
||||
assert "контакт" not in sent[0]
|
||||
assert "@durovtest" in sent[0]
|
||||
assert b"@durovtest" not in _db_bytes(db_path)
|
||||
|
||||
|
||||
# --- 3. Kill-switch регистрации ---
|
||||
|
||||
Reference in New Issue
Block a user