feat: мульти-пользовательская авторизация через invite + email

- SQLite: таблицы users (email, password_hash, role, verified) + invites
- auth.py: register_user, verify_email, hash_password + legacy env user
- email_service.py: SMTP Timeweb (smtp.timeweb.ru:465) — код подтверждения
- API: POST /api/register, /api/verify-email, /api/admin/invite
- UI: /register?invite=TOKEN — 3-шаговая регистрация
- Admin: кнопка создать приглашение, список invites + users
- Обратная совместимость: env user (smeta) = admin

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-27 15:44:43 +10:00
co-authored by Claude Opus 4.6
parent 144a592e5e
commit 0469dd85e7
7 changed files with 523 additions and 19 deletions
+106 -16
View File
@@ -1,26 +1,33 @@
"""JWT authentication — single user from env vars."""
"""JWT authentication — multi-user with invite-based registration.
Supports:
1. Legacy env-var user (SMETA_USER/SMETA_PASS) — admin
2. Registered users from SQLite (email + password)
"""
import hashlib
import hmac
import logging
import os
import secrets
import time
from jose import jwt
logger = logging.getLogger(__name__)
# #1 CRITICAL: no fallback — fail loudly if not set
SECRET = os.environ.get("SESSION_SECRET", "")
if not SECRET:
logger.warning("SESSION_SECRET not set! Auth will reject all tokens.")
logger.warning("SESSION_SECRET not set!")
ALGORITHM = "HS256"
TOKEN_EXPIRE = 86400 # 24 hours (was 7 days — #11)
TOKEN_EXPIRE = 86400 # 24 hours
VALID_USER = os.environ.get("SMETA_USER", "")
VALID_PASS = os.environ.get("SMETA_PASS", "")
# Legacy single user (admin)
LEGACY_USER = os.environ.get("SMETA_USER", "")
LEGACY_PASS = os.environ.get("SMETA_PASS", "")
# Login rate limiting (#5)
# Rate limiting
_login_attempts: dict[str, list[float]] = {}
MAX_ATTEMPTS = 5
LOCKOUT_SECONDS = 300
@@ -29,7 +36,6 @@ LOCKOUT_SECONDS = 300
def _is_locked(ip: str) -> bool:
now = time.time()
attempts = _login_attempts.get(ip, [])
# Remove old attempts
attempts = [t for t in attempts if now - t < LOCKOUT_SECONDS]
_login_attempts[ip] = attempts
return len(attempts) >= MAX_ATTEMPTS
@@ -39,26 +45,99 @@ def _record_attempt(ip: str):
_login_attempts.setdefault(ip, []).append(time.time())
def hash_password(password: str) -> str:
"""Hash password with salt using SHA-256."""
salt = secrets.token_hex(16)
h = hashlib.sha256((salt + password).encode()).hexdigest()
return f"{salt}:{h}"
def check_password(password: str, password_hash: str) -> bool:
"""Verify password against stored hash."""
if ":" not in password_hash:
return False
salt, h = password_hash.split(":", 1)
return hmac.compare_digest(
hashlib.sha256((salt + password).encode()).hexdigest(), h
)
def _make_token(username: str, role: str = "user") -> str:
"""Create JWT token."""
payload = {
"sub": username,
"role": role,
"exp": int(time.time()) + TOKEN_EXPIRE,
}
return jwt.encode(payload, SECRET, algorithm=ALGORITHM)
def authenticate(username: str, password: str, client_ip: str = "") -> str | None:
"""Return JWT token if credentials are valid, else None."""
if not SECRET or not VALID_PASS or not VALID_USER:
"""Authenticate user. Tries legacy env user first, then SQLite.
Returns JWT token or None.
"""
if not SECRET:
return None
if client_ip and _is_locked(client_ip):
return None
# #4 HIGH: constant-time comparison
user_ok = hmac.compare_digest(username, VALID_USER)
pass_ok = hmac.compare_digest(password, VALID_PASS)
# 1. Legacy admin user from env vars
if LEGACY_USER and LEGACY_PASS:
if hmac.compare_digest(username, LEGACY_USER) and hmac.compare_digest(password, LEGACY_PASS):
return _make_token(username, role="admin")
if user_ok and pass_ok:
payload = {"sub": username, "exp": int(time.time()) + TOKEN_EXPIRE}
return jwt.encode(payload, SECRET, algorithm=ALGORITHM)
# 2. Registered users from SQLite
from db import get_user_by_email
user = get_user_by_email(username) # username = email
if user and user["verified"] and check_password(password, user["password_hash"]):
return _make_token(user["email"], role=user["role"])
if client_ip:
_record_attempt(client_ip)
return None
def register_user(email: str, password: str, invite_token: str) -> dict:
"""Register new user with invite token.
Returns {"ok": True, "message": ...} or {"ok": False, "error": ...}.
"""
from db import get_user_by_email, create_user, use_invite, set_verify_code
email = email.lower().strip()
if not email or "@" not in email:
return {"ok": False, "error": "Некорректный email"}
if len(password) < 6:
return {"ok": False, "error": "Пароль минимум 6 символов"}
# Check invite
if not use_invite(invite_token, email):
return {"ok": False, "error": "Недействительная или использованная ссылка-приглашение"}
# Check existing user
if get_user_by_email(email):
return {"ok": False, "error": "Пользователь с таким email уже существует"}
# Create user
pw_hash = hash_password(password)
create_user(email, pw_hash)
# Generate verification code
code = f"{secrets.randbelow(1000000):06d}"
set_verify_code(email, code)
return {"ok": True, "message": "Код подтверждения отправлен на email", "code": code}
def verify_email(email: str, code: str) -> dict:
"""Verify email with code. Returns {"ok": True} or {"ok": False, "error": ...}."""
from db import verify_user
if verify_user(email, code):
return {"ok": True, "message": "Email подтверждён. Можете войти."}
return {"ok": False, "error": "Неверный или просроченный код"}
def verify_token(token: str) -> str | None:
"""Return username if token is valid, else None."""
if not SECRET:
@@ -68,3 +147,14 @@ def verify_token(token: str) -> str | None:
return payload.get("sub")
except Exception:
return None
def get_token_role(token: str) -> str:
"""Return role from token (admin/user)."""
if not SECRET:
return "user"
try:
payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
return payload.get("role", "user")
except Exception:
return "user"
+109
View File
@@ -18,6 +18,27 @@ CREATE TABLE IF NOT EXISTS messages (
timestamp REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_session ON messages(username, tab_id);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
verified INTEGER NOT NULL DEFAULT 0,
verify_code TEXT,
verify_expires REAL,
created_at REAL NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE TABLE IF NOT EXISTS invites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token TEXT UNIQUE NOT NULL,
created_by TEXT NOT NULL,
used_by TEXT,
created_at REAL NOT NULL,
expires_at REAL NOT NULL
);
"""
@@ -53,6 +74,94 @@ def get_history(username: str, tab_id: str, limit: int = 100) -> list[dict]:
return [dict(r) for r in reversed(rows)]
# === Users ===
def create_user(email: str, password_hash: str, role: str = "user") -> int:
with _conn() as conn:
cur = conn.execute(
"INSERT INTO users (email, password_hash, role, created_at) VALUES (?, ?, ?, ?)",
(email.lower().strip(), password_hash, role, time.time()),
)
return cur.lastrowid
def get_user_by_email(email: str) -> dict | None:
with _conn() as conn:
row = conn.execute(
"SELECT * FROM users WHERE email = ?", (email.lower().strip(),)
).fetchone()
return dict(row) if row else None
def set_verify_code(email: str, code: str, expires_in: int = 600):
with _conn() as conn:
conn.execute(
"UPDATE users SET verify_code = ?, verify_expires = ? WHERE email = ?",
(code, time.time() + expires_in, email.lower().strip()),
)
def verify_user(email: str, code: str) -> bool:
with _conn() as conn:
user = conn.execute(
"SELECT verify_code, verify_expires FROM users WHERE email = ?",
(email.lower().strip(),),
).fetchone()
if not user or user["verify_code"] != code:
return False
if user["verify_expires"] and time.time() > user["verify_expires"]:
return False
conn.execute(
"UPDATE users SET verified = 1, verify_code = NULL WHERE email = ?",
(email.lower().strip(),),
)
return True
def list_users() -> list[dict]:
with _conn() as conn:
rows = conn.execute(
"SELECT id, email, role, verified, created_at FROM users ORDER BY created_at DESC"
).fetchall()
return [dict(r) for r in rows]
# === Invites ===
def create_invite(token: str, created_by: str, expires_hours: int = 72) -> int:
with _conn() as conn:
cur = conn.execute(
"INSERT INTO invites (token, created_by, created_at, expires_at) VALUES (?, ?, ?, ?)",
(token, created_by, time.time(), time.time() + expires_hours * 3600),
)
return cur.lastrowid
def use_invite(token: str, used_by: str) -> bool:
with _conn() as conn:
invite = conn.execute(
"SELECT * FROM invites WHERE token = ? AND used_by IS NULL",
(token,),
).fetchone()
if not invite:
return False
if time.time() > invite["expires_at"]:
return False
conn.execute(
"UPDATE invites SET used_by = ? WHERE token = ?",
(used_by, token),
)
return True
def list_invites() -> list[dict]:
with _conn() as conn:
rows = conn.execute(
"SELECT token, created_by, used_by, created_at, expires_at FROM invites ORDER BY created_at DESC LIMIT 50"
).fetchall()
return [dict(r) for r in rows]
def list_sessions(username: str) -> list[dict]:
"""List all chat sessions for a user with last message preview."""
with _conn() as conn:
+53
View File
@@ -0,0 +1,53 @@
"""Email service — send verification codes via SMTP (Timeweb)."""
import logging
import os
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
logger = logging.getLogger(__name__)
SMTP_HOST = os.environ.get("SMTP_HOST", "smtp.timeweb.ru")
SMTP_PORT = int(os.environ.get("SMTP_PORT", "465"))
SMTP_USER = os.environ.get("SMTP_USER", "")
SMTP_PASS = os.environ.get("SMTP_PASS", "")
def send_verification_code(to_email: str, code: str) -> bool:
"""Send 6-digit verification code to email. Returns True on success."""
if not SMTP_USER or not SMTP_PASS:
logger.warning("SMTP not configured, skipping email to %s", to_email)
return False
subject = "Код подтверждения — Сметный ИИ-ассистент"
html = f"""
<div style="font-family: Arial, sans-serif; max-width: 400px; margin: 0 auto; padding: 20px;">
<h2 style="color: #3a3a3a;">Сметный ИИ-ассистент</h2>
<p>Ваш код подтверждения:</p>
<div style="background: #f5f0eb; padding: 15px; border-radius: 8px; text-align: center; margin: 20px 0;">
<span style="font-size: 32px; font-weight: bold; letter-spacing: 8px; color: #c4463a;">{code}</span>
</div>
<p style="color: #6b6b6b; font-size: 14px;">Код действителен 10 минут.</p>
<p style="color: #6b6b6b; font-size: 12px;">Если вы не регистрировались — проигнорируйте это письмо.</p>
</div>
"""
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = f"Сметный ассистент <{SMTP_USER}>"
msg["To"] = to_email
msg.attach(MIMEText(f"Ваш код подтверждения: {code}\nДействителен 10 минут.", "plain", "utf-8"))
msg.attach(MIMEText(html, "html", "utf-8"))
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context, timeout=10) as server:
server.login(SMTP_USER, SMTP_PASS)
server.sendmail(SMTP_USER, to_email, msg.as_string())
logger.info("Verification email sent to %s", to_email)
return True
except Exception as e:
logger.error("Failed to send email to %s: %s", to_email, e)
return False
+70
View File
@@ -121,6 +121,47 @@ async def login(request: Request):
return {"token": token, "username": username}
@app.post("/api/register")
async def register(request: Request):
body = await request.json()
email = body.get("email", "")
password = body.get("password", "")
invite = body.get("invite", "")
from auth import register_user
result = register_user(email, password, invite)
if not result["ok"]:
raise HTTPException(400, result["error"])
# Send verification code via email
code = result.get("code", "")
if code:
from email_service import send_verification_code
sent = send_verification_code(email, code)
if not sent:
return {"message": "Аккаунт создан, но email не отправлен. Обратитесь к администратору."}
return {"message": result["message"]}
@app.post("/api/verify-email")
async def verify_email_endpoint(request: Request):
body = await request.json()
email = body.get("email", "")
code = body.get("code", "")
from auth import verify_email
result = verify_email(email, code)
if not result["ok"]:
raise HTTPException(400, result["error"])
return {"message": result["message"]}
@app.get("/register", response_class=HTMLResponse)
async def register_page():
return Path("static/register.html").read_text(encoding="utf-8")
async def _stream_and_save(message: str, user: str, tab_id: str):
"""Wrap stream_claude to save messages to DB."""
save_message(user, tab_id, "user", message)
@@ -586,6 +627,35 @@ async def admin_stats(request: Request):
return {"daily": [dict(r) for r in daily], "totals": dict(totals)}
@app.post("/api/admin/invite")
async def create_invite_endpoint(request: Request):
"""Create invite link. Admin only."""
user = _get_user(request)
from auth import get_token_role
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
if get_token_role(token) != "admin":
raise HTTPException(403, "Admin only")
import secrets
from db import create_invite
invite_token = secrets.token_urlsafe(24)
create_invite(invite_token, user)
return {"invite_token": invite_token, "url": f"https://smeta.kazin.ru/register?invite={invite_token}"}
@app.get("/api/admin/invites")
async def list_invites_endpoint(request: Request):
_get_user(request)
from db import list_invites
return list_invites()
@app.get("/api/admin/users")
async def list_users_endpoint(request: Request):
_get_user(request)
from db import list_users
return list_users()
@app.get("/admin", response_class=HTMLResponse)
async def admin_page():
return Path("static/admin.html").read_text(encoding="utf-8")
+59 -2
View File
@@ -23,6 +23,21 @@ a:hover { text-decoration: underline; }
<h1>Dashboard</h1>
<div id="stats" style="display:flex;gap:1rem;margin-bottom:1.5rem;flex-wrap:wrap"></div>
<div id="daily" style="margin-bottom:1.5rem"></div>
<div style="display:flex;gap:.5rem;margin-bottom:1.5rem">
<button onclick="createInvite()" style="padding:.5rem 1rem;background:#c4463a;color:#fff;border:none;border-radius:6px;cursor:pointer;font-weight:600">Создать приглашение</button>
</div>
<div id="invite-result" style="margin-bottom:1rem;font-size:.85rem"></div>
<h2 style="font-size:1rem;margin-bottom:.5rem">Приглашения</h2>
<table id="invites" style="margin-bottom:1.5rem">
<tr><th>Ссылка</th><th>Создано</th><th>Использовано</th></tr>
</table>
<h2 style="font-size:1rem;margin-bottom:.5rem">Пользователи</h2>
<table id="users" style="margin-bottom:1.5rem">
<tr><th>Email</th><th>Роль</th><th>Подтверждён</th><th>Создан</th></tr>
</table>
<h2 style="font-size:1rem;margin-bottom:.5rem">Сессии</h2>
<table id="sessions">
<tr><th>Время</th><th>Пользователь</th><th>Сообщений</th><th>Последний вопрос</th><th></th></tr>
@@ -32,8 +47,50 @@ a:hover { text-decoration: underline; }
const token = localStorage.getItem('token');
if (!token) window.location.href = '/';
const H = {'Authorization': 'Bearer ' + token};
// Create invite
async function createInvite() {
const r = await fetch('/api/admin/invite', {method:'POST', headers: H});
const d = await r.json();
if (d.url) {
document.getElementById('invite-result').innerHTML = '<b>Ссылка:</b> <a href="' + d.url + '" target="_blank">' + d.url + '</a> <button onclick="navigator.clipboard.writeText(\'' + d.url + '\');this.textContent=\'Скопировано\'" style="padding:2px 8px;font-size:.75rem;cursor:pointer">Копировать</button>';
loadInvites();
} else {
document.getElementById('invite-result').textContent = d.detail || 'Ошибка';
}
}
// Load invites
function loadInvites() {
fetch('/api/admin/invites', {headers: H}).then(r=>r.json()).then(invites => {
const t = document.getElementById('invites');
t.innerHTML = '<tr><th>Ссылка</th><th>Создано</th><th>Использовано</th></tr>';
for (const i of invites) {
const d = new Date(i.created_at < 1e12 ? i.created_at*1000 : i.created_at);
const tr = document.createElement('tr');
const url = 'https://smeta.kazin.ru/register?invite=' + i.token;
const used = i.used_by || '—';
tr.innerHTML = '<td style="font-size:.75rem;word-break:break-all;max-width:300px"><a href="'+url+'" target="_blank">'+i.token.slice(0,12)+'...</a></td><td class="time">'+d.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})+'</td><td style="font-size:.8rem">'+used+'</td>';
t.appendChild(tr);
}
});
}
loadInvites();
// Load users
fetch('/api/admin/users', {headers: H}).then(r=>r.json()).then(users => {
const t = document.getElementById('users');
for (const u of users) {
const d = new Date(u.created_at < 1e12 ? u.created_at*1000 : u.created_at);
const tr = document.createElement('tr');
tr.innerHTML = '<td>'+u.email+'</td><td>'+u.role+'</td><td>'+(u.verified?'Да':'Нет')+'</td><td class="time">'+d.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})+'</td>';
t.appendChild(tr);
}
});
// Stats
fetch('/api/admin/stats', {headers: {'Authorization': 'Bearer ' + token}})
fetch('/api/admin/stats', {headers: H})
.then(r => r.json())
.then(data => {
const t = data.totals;
@@ -51,7 +108,7 @@ fetch('/api/admin/stats', {headers: {'Authorization': 'Bearer ' + token}})
});
// Sessions
fetch('/api/admin/sessions', {headers: {'Authorization': 'Bearer ' + token}})
fetch('/api/admin/sessions', {headers: H})
.then(r => r.json())
.then(sessions => {
const table = document.getElementById('sessions');
+2 -1
View File
@@ -107,9 +107,10 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
<h2>Сметный ИИ</h2>
<span class="subtitle">Профессиональный ассистент</span>
<div id="login-error">Неверный логин или пароль</div>
<input type="text" id="login-user" placeholder="Логин" autocomplete="username" required>
<input type="text" id="login-user" placeholder="Email или логин" autocomplete="username" required>
<input type="password" id="login-pass" placeholder="Пароль" autocomplete="current-password" required>
<button type="submit">Войти</button>
<p style="text-align:center;margin-top:.8rem;font-size:.85rem;color:var(--text-muted)">Нет аккаунта? Попросите приглашение у администратора</p>
</form>
</div>
+124
View File
@@ -0,0 +1,124 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Регистрация — Сметный ИИ-ассистент</title>
<style>
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
.card { background: var(--card); border-radius: var(--radius); padding: 2rem; width: 380px; box-shadow: 0 2px 12px rgba(0,0,0,.08); }
h1 { font-size: 1.2rem; margin-bottom: .3rem; }
.subtitle { color: var(--muted); font-size: .85rem; margin-bottom: 1.5rem; }
label { display: block; font-weight: 600; margin-bottom: .3rem; font-size: .85rem; }
input { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .9rem; margin-bottom: 1rem; font-family: inherit; }
input:focus { outline: none; border-color: var(--accent); }
button { width: 100%; padding: .7rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
button:hover { background: #a83830; }
button:disabled { background: var(--border); cursor: not-allowed; }
.error { color: var(--accent); font-size: .85rem; margin-bottom: .5rem; display: none; }
.success { color: var(--green); font-size: .85rem; margin-bottom: .5rem; display: none; }
.link { color: var(--accent); text-decoration: none; font-size: .85rem; }
.link:hover { text-decoration: underline; }
.step { display: none; }
.step.active { display: block; }
</style>
</head>
<body>
<div class="card">
<h1>Регистрация</h1>
<p class="subtitle">Сметный ИИ-ассистент</p>
<!-- Step 1: Email + Password -->
<div class="step active" id="step1">
<div class="error" id="err1"></div>
<label>Email</label>
<input type="email" id="reg-email" placeholder="your@email.com">
<label>Пароль</label>
<input type="password" id="reg-pass" placeholder="Минимум 6 символов">
<label>Повторите пароль</label>
<input type="password" id="reg-pass2" placeholder="Повторите пароль">
<button onclick="doRegister()">Зарегистрироваться</button>
<p style="margin-top:1rem;text-align:center"><a class="link" href="/">Уже есть аккаунт? Войти</a></p>
</div>
<!-- Step 2: Verification code -->
<div class="step" id="step2">
<div class="success" id="msg2"></div>
<div class="error" id="err2"></div>
<label>Код подтверждения</label>
<p style="color:var(--muted);font-size:.8rem;margin-bottom:.5rem">Код отправлен на <b id="sent-email"></b></p>
<input type="text" id="verify-code" placeholder="000000" maxlength="6" style="text-align:center;font-size:1.5rem;letter-spacing:8px">
<button onclick="doVerify()">Подтвердить</button>
</div>
<!-- Step 3: Success -->
<div class="step" id="step3">
<div class="success" style="display:block">Email подтверждён! Можете войти.</div>
<br>
<button onclick="window.location.href='/'">Войти</button>
</div>
</div>
<script>
// Get invite token from URL
const params = new URLSearchParams(window.location.search);
const inviteToken = params.get('invite') || '';
let regEmail = '';
function showStep(n) {
document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
document.getElementById('step' + n).classList.add('active');
}
async function doRegister() {
const email = document.getElementById('reg-email').value.trim();
const pass = document.getElementById('reg-pass').value;
const pass2 = document.getElementById('reg-pass2').value;
const err = document.getElementById('err1');
err.style.display = 'none';
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; }
if (!inviteToken) { err.textContent = 'Нужна ссылка-приглашение от администратора'; err.style.display = 'block'; return; }
try {
const r = await fetch('/api/register', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email, password: pass, invite: inviteToken}),
});
const data = await r.json();
if (!r.ok) { err.textContent = data.detail || 'Ошибка регистрации'; err.style.display = 'block'; return; }
regEmail = email;
document.getElementById('sent-email').textContent = email;
document.getElementById('msg2').textContent = data.message;
document.getElementById('msg2').style.display = 'block';
showStep(2);
} catch(e) { err.textContent = 'Ошибка сети'; err.style.display = 'block'; }
}
async function doVerify() {
const code = document.getElementById('verify-code').value.trim();
const err = document.getElementById('err2');
err.style.display = 'none';
if (!code) { err.textContent = 'Введите код'; err.style.display = 'block'; return; }
try {
const r = await fetch('/api/verify-email', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email: regEmail, code}),
});
const data = await r.json();
if (!r.ok) { err.textContent = data.detail || 'Неверный код'; err.style.display = 'block'; return; }
showStep(3);
} catch(e) { err.textContent = 'Ошибка сети'; err.style.display = 'block'; }
}
</script>
</body>
</html>