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
+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>