feat(вход): восстановление доступа по письму и честная причина отказа
Живой случай 08.09.2026: человек с верным паролем читал «неверный логин или пароль» (вход отбивала неподтверждённая почта), а восстановить доступ было нечем — он оказался заперт. Теперь на странице входа есть «Забыли пароль?», код приходит письмом, пароль меняется тут же; причину отказа показывает сервер, а не выдумка страницы. Повторная регистрация на неподтверждённую почту продолжает её, а не отбивает. Отказ сервера при запросе кода больше не выдаётся за успех (нашли оба рецензента), форму нельзя отправить дважды, код восстановления сгорает ровно один раз. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RuEU1u9Rz24zmoy9TuvWc2
This commit is contained in:
+160
-18
@@ -47,7 +47,9 @@ button { font-family: inherit; }
|
||||
/* Лендинг-витрина для незалогиненного (1.2/5.3): герой + примеры + форма входа.
|
||||
Центрирование через margin:auto на .landing (не align-items:center) — иначе при
|
||||
переполнении по высоте флекс-центрирование обрезает верх без возможности доскроллить. */
|
||||
#login-screen { display: flex; height: 100vh; overflow-y: auto; background: linear-gradient(135deg, #f5f0eb 0%, #ede5db 100%); }
|
||||
#login-screen { display: flex; flex-direction: column; height: 100vh; overflow-y: auto; background: linear-gradient(135deg, #f5f0eb 0%, #ede5db 100%); }
|
||||
/* Полоса «сайт в разработке»: только цвета темы, чтобы читалась и в тёмной */
|
||||
#dev-banner { flex: 0 0 auto; padding: .6rem var(--s4); text-align: center; font-size: .88rem; line-height: 1.4; color: var(--text); background: var(--accent-light); border-bottom: 2px solid var(--accent); }
|
||||
.landing { margin: auto; display: flex; align-items: center; gap: var(--s6); max-width: 1060px; padding: var(--s6) var(--s4); }
|
||||
.landing-hero { flex: 1 1 auto; min-width: 0; }
|
||||
.landing-hero h1 { font-size: 1.6rem; line-height: 1.25; letter-spacing: -.015em; margin-bottom: .55rem; color: var(--text); }
|
||||
@@ -70,15 +72,15 @@ button { font-family: inherit; }
|
||||
.landing-login { flex: 0 0 auto; align-self: center; width: 100%; max-width: 380px; }
|
||||
.landing-hero h1 { font-size: 1.35rem; }
|
||||
}
|
||||
#login-form { background: var(--bg-card); padding: 2.5rem 2rem; border-radius: var(--radius-lg); box-shadow: var(--shadow-md); width: 340px; }
|
||||
.landing-login #login-form { width: 100%; }
|
||||
#login-form h2 { margin-bottom: .3rem; text-align: center; font-size: 1.4rem; font-weight: 700; color: var(--text); }
|
||||
#login-form .subtitle { text-align: center; color: var(--text-muted); font-size: .85rem; margin-bottom: 1.5rem; display: block; }
|
||||
#login-form input { width: 100%; padding: .7rem .9rem; margin-bottom: .7rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; transition: border-color .2s; outline: none; background: var(--bg); }
|
||||
#login-form input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
#login-form button { width: 100%; padding: .75rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; transition: background .2s; margin-top: .3rem; }
|
||||
#login-form button:hover { background: var(--accent-hover); }
|
||||
#login-form button:active { background: var(--accent-active); transform: translateY(1px); }
|
||||
#login-form, #reset-form { background: var(--bg-card); padding: 2.5rem 2rem; border-radius: var(--radius-lg); box-shadow: var(--shadow-md); width: 340px; }
|
||||
.landing-login #login-form, .landing-login #reset-form { width: 100%; }
|
||||
#login-form h2, #reset-form h2 { margin-bottom: .3rem; text-align: center; font-size: 1.4rem; font-weight: 700; color: var(--text); }
|
||||
#login-form .subtitle, #reset-form .subtitle { text-align: center; color: var(--text-muted); font-size: .85rem; margin-bottom: 1.5rem; display: block; }
|
||||
#login-form input, #reset-form input { width: 100%; padding: .7rem .9rem; margin-bottom: .7rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; transition: border-color .2s; outline: none; background: var(--bg); }
|
||||
#login-form input:focus, #reset-form input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||||
#login-form button, #reset-form button { width: 100%; padding: .75rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; transition: background .2s; margin-top: .3rem; }
|
||||
#login-form button:hover, #reset-form button:hover { background: var(--accent-hover); }
|
||||
#login-form button:active, #reset-form button:active { background: var(--accent-active); transform: translateY(1px); }
|
||||
|
||||
/* Инлайн-панель «Пригласить коллегу» (5.1): обычный поток под шапкой, НЕ попап */
|
||||
#invite-panel { background: var(--bg-card); border-bottom: 1px solid var(--border-light); padding: .55rem 1.4rem .65rem; }
|
||||
@@ -90,7 +92,10 @@ button { font-family: inherit; }
|
||||
#invite-panel button.copied { background: #d3f9d8; border-color: #69db7c; color: #2b8a3e; }
|
||||
:root[data-theme="dark"] #invite-panel button.copied { background: #1e3a25; border-color: #2f6b40; color: #86dca0; }
|
||||
#invite-error { font-size: .78rem; color: var(--accent); margin-top: .3rem; }
|
||||
#login-error { color: #e03131; font-size: .8rem; margin-bottom: .5rem; display: none; text-align: center; }
|
||||
#login-error, #reset-error { color: #e03131; font-size: .8rem; margin-bottom: .5rem; display: none; text-align: center; }
|
||||
#login-notice, #reset-notice { color: var(--ok); font-size: .8rem; margin-bottom: .5rem; display: none; text-align: center; }
|
||||
.reset-hint { color: var(--text-muted); font-size: .78rem; margin-bottom: .6rem; text-align: center; line-height: 1.4; }
|
||||
#reset-form button[disabled] { opacity: .6; cursor: default; }
|
||||
|
||||
/* Chat */
|
||||
#chat-screen { display: none; flex-direction: column; height: 100vh; }
|
||||
@@ -230,6 +235,10 @@ button { font-family: inherit; }
|
||||
#file-btn { padding: .65rem .7rem; background: var(--bg-sunken); border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: 1.1rem; line-height: 1; transition: all .15s; }
|
||||
#file-btn:hover { border-color: var(--accent); background: var(--accent-light); }
|
||||
#file-btn:active { transform: translateY(1px); }
|
||||
/* Адрес для обратной связи: читаемый, без прозрачности соседней служебной строки */
|
||||
#contact-line { margin-top: .25rem; text-align: center; font-size: .7rem; line-height: 1.3; color: var(--text-muted); }
|
||||
#contact-line a { color: var(--text-muted); text-decoration: underline; text-underline-offset: 2px; }
|
||||
#contact-line a:hover { color: var(--accent); }
|
||||
|
||||
/* Layout with left chat sidebar (Claude-desktop style) */
|
||||
.app-layout { flex: 1; display: flex; min-height: 0; }
|
||||
@@ -292,7 +301,7 @@ html { color-scheme: light; }
|
||||
}
|
||||
/* Места с захардкоженным цветом — переопределяем только в тёмной (light не трогаем) */
|
||||
:root[data-theme="dark"] #login-screen { background: linear-gradient(135deg, #1b1813 0%, #131009 100%); }
|
||||
:root[data-theme="dark"] #login-error,
|
||||
:root[data-theme="dark"] #login-error, :root[data-theme="dark"] #reset-error,
|
||||
:root[data-theme="dark"] .msg-error { color: #ff8585; }
|
||||
:root[data-theme="dark"] .msg-tool { background: #2a2410; border-color: #4a3f1a; color: #ecc879; }
|
||||
:root[data-theme="dark"] .msg-file a { color: #5fc27e; }
|
||||
@@ -328,6 +337,7 @@ html { color-scheme: light; }
|
||||
<!-- Login Screen = публичный лендинг-витрина (1.2/5.3): герой + примеры + форма входа.
|
||||
Все примеры в галерее СИНТЕТИЧЕСКИЕ — никаких реальных смет/клиентов/реквизитов. -->
|
||||
<div id="login-screen" style="display:none">
|
||||
<div id="dev-banner" role="note"><strong>Сайт ещё в разработке.</strong> Возможны ошибки и перебои в работе — сервис дорабатывается. Спасибо за понимание.</div>
|
||||
<div class="landing">
|
||||
<section class="landing-hero" aria-label="О сервисе">
|
||||
<h1>Сметный ИИ — проверка смет и нормативные ответы для сметчиков</h1>
|
||||
@@ -364,11 +374,31 @@ html { color-scheme: light; }
|
||||
<form id="login-form" onsubmit="return doLogin(event)">
|
||||
<h2>Сметный ИИ</h2>
|
||||
<span class="subtitle">Профессиональный ассистент</span>
|
||||
<div id="login-notice" role="status"></div>
|
||||
<div id="login-error" role="alert"></div>
|
||||
<input type="text" id="login-user" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||||
<input type="text" id="login-user" aria-describedby="dev-banner" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" aria-label="Пароль" autocomplete="current-password" required>
|
||||
<button type="submit">Войти</button>
|
||||
<p class="register-link">Нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
|
||||
<p class="register-link"><a href="#" id="forgot-link" onclick="return openReset(event)">Забыли пароль?</a></p>
|
||||
</form>
|
||||
<!-- Восстановление доступа: без него человек с неподтверждённой почтой оказывался заперт -->
|
||||
<form id="reset-form" novalidate style="display:none" onsubmit="return doReset(event)">
|
||||
<h2>Восстановление доступа</h2>
|
||||
<span class="subtitle">Пришлём код на почту</span>
|
||||
<div id="reset-error" role="alert"></div>
|
||||
<div id="reset-notice" role="status"></div>
|
||||
<div id="reset-step-1">
|
||||
<input type="email" id="reset-email" placeholder="Email при регистрации" aria-label="Email" autocomplete="username">
|
||||
<button type="submit">Прислать код</button>
|
||||
</div>
|
||||
<div id="reset-step-2" style="display:none">
|
||||
<p id="reset-sent-to" class="reset-hint"></p>
|
||||
<input type="text" id="reset-code" placeholder="Код из письма" aria-label="Код из письма" inputmode="numeric" maxlength="6" autocomplete="one-time-code">
|
||||
<input type="password" id="reset-pass" placeholder="Новый пароль (от 6 знаков)" aria-label="Новый пароль" autocomplete="new-password">
|
||||
<button type="submit">Сохранить пароль</button>
|
||||
</div>
|
||||
<p class="register-link"><a href="#" id="reset-back" onclick="return closeReset(event)">Вернуться ко входу</a></p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -461,6 +491,8 @@ html { color-scheme: light; }
|
||||
</div>
|
||||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||||
<div style="text-align:center;margin-top:4px"><a href="/static/security.html" target="_blank" style="font-size:.65rem;color:var(--text-muted);opacity:.4;text-decoration:none">О безопасности сервиса</a><span class="app-version" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span><span class="data-version" title="Период, на который актуальны цены корпусной базы" style="font-size:.65rem;color:var(--text-muted);opacity:.4;margin-left:.6rem"></span></div>
|
||||
<!-- Адрес для обратной связи (08.09.2026): вне ленты, иначе стирается при новом чате -->
|
||||
<p id="contact-line">Обратная связь: <a id="contact-email" href="mailto:info@infosmeta.ru">info@infosmeta.ru</a></p>
|
||||
</div>
|
||||
</div><!-- /.main-col -->
|
||||
</div><!-- /.app-layout -->
|
||||
@@ -908,6 +940,8 @@ function checkAdmin() {
|
||||
function showLogin() {
|
||||
document.getElementById('login-screen').style.display = 'flex';
|
||||
document.getElementById('chat-screen').style.display = 'none';
|
||||
document.getElementById('login-pass').value = ''; // чужой пароль в поле после выхода не оставляем
|
||||
hideBox('login-error'); hideBox('login-notice');
|
||||
// a11y: фокус на форме входа; preventScroll — на узком экране форма ПОД героем,
|
||||
// автопрокрутка мимо лендинга запрещена (анти-навязчивость)
|
||||
try { document.getElementById('login-user').focus({preventScroll: true}); } catch (e) {}
|
||||
@@ -923,17 +957,43 @@ function showChat() {
|
||||
}
|
||||
|
||||
// --- Auth ---
|
||||
// Причину отказа берём У СЕРВЕРА: 08.09.2026 человек с верным паролем читал «неверный
|
||||
// логин или пароль», хотя вход отбивало неподтверждённой почтой, и починить это он не мог.
|
||||
async function serverReason(r, fallback) {
|
||||
try {
|
||||
const d = (await r.json()).detail;
|
||||
if (typeof d === 'string' && d.trim()) return d.trim(); // список от проверки полей — не текст для человека
|
||||
} catch (e) {}
|
||||
return fallback;
|
||||
}
|
||||
const _boxTimers = {};
|
||||
function showBox(id, text) {
|
||||
const el = document.getElementById(id);
|
||||
el.textContent = ''; // очистка+переустановка гарантирует объявление role=alert
|
||||
el.style.display = 'block';
|
||||
clearTimeout(_boxTimers[id]);
|
||||
_boxTimers[id] = setTimeout(() => { el.textContent = text; }, 30);
|
||||
}
|
||||
function hideBox(id) {
|
||||
const el = document.getElementById(id);
|
||||
clearTimeout(_boxTimers[id]); // иначе текст ляжет в уже спрятанный блок
|
||||
el.textContent = ''; el.style.display = 'none';
|
||||
}
|
||||
async function doLogin(e) {
|
||||
e.preventDefault();
|
||||
const user = document.getElementById('login-user').value;
|
||||
const pass = document.getElementById('login-pass').value;
|
||||
hideBox('login-notice');
|
||||
try {
|
||||
const r = await fetch(API + '/api/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({username: user, password: pass})
|
||||
});
|
||||
if (!r.ok) throw new Error();
|
||||
if (!r.ok) {
|
||||
showBox('login-error', await serverReason(r, 'Не удалось войти. Проверьте почту и пароль.'));
|
||||
return false;
|
||||
}
|
||||
const data = await r.json();
|
||||
token = data.token;
|
||||
localStorage.setItem('token', token);
|
||||
@@ -941,13 +1001,95 @@ async function doLogin(e) {
|
||||
checkAdmin();
|
||||
showChat(); // loadHistory сам покажет онбординг на пустом чате
|
||||
} catch {
|
||||
const le = document.getElementById('login-error');
|
||||
le.textContent = ''; // очистка+переустановка гарантирует объявление role=alert
|
||||
le.style.display = 'block';
|
||||
setTimeout(() => { le.textContent = 'Неверный логин или пароль'; }, 30);
|
||||
showBox('login-error', 'Не получилось связаться с сервером. Попробуйте ещё раз.');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- Восстановление доступа ---
|
||||
function openReset(e) {
|
||||
if (e) e.preventDefault();
|
||||
hideBox('login-error'); hideBox('login-notice'); hideBox('reset-error'); hideBox('reset-notice');
|
||||
document.getElementById('login-form').style.display = 'none';
|
||||
document.getElementById('reset-form').style.display = '';
|
||||
document.getElementById('reset-step-1').style.display = '';
|
||||
document.getElementById('reset-step-2').style.display = 'none';
|
||||
document.getElementById('reset-code').value = '';
|
||||
document.getElementById('reset-pass').value = '';
|
||||
const em = document.getElementById('reset-email');
|
||||
em.value = document.getElementById('login-user').value.trim();
|
||||
em.focus();
|
||||
return false;
|
||||
}
|
||||
function closeReset(e) {
|
||||
if (e) e.preventDefault();
|
||||
document.getElementById('reset-form').style.display = 'none';
|
||||
document.getElementById('login-form').style.display = '';
|
||||
document.getElementById('reset-code').value = '';
|
||||
document.getElementById('reset-pass').value = ''; // новый пароль в поле не оставляем
|
||||
hideBox('reset-error'); hideBox('reset-notice');
|
||||
return false;
|
||||
}
|
||||
let resetBusy = false;
|
||||
async function doReset(e) {
|
||||
e.preventDefault();
|
||||
if (resetBusy) return false; // Enter в поле шлёт форму мимо запертой кнопки
|
||||
const onCode = document.getElementById('reset-step-2').style.display !== 'none';
|
||||
const btn = document.querySelector((onCode ? '#reset-step-2' : '#reset-step-1') + ' button[type=submit]');
|
||||
const email = document.getElementById('reset-email').value.trim();
|
||||
hideBox('reset-error');
|
||||
if (!onCode) {
|
||||
if (email.indexOf('@') < 1) { // форма без встроенной проверки браузера — сторожим сами
|
||||
showBox('reset-error', 'Укажите почту, на которую регистрировались');
|
||||
return false;
|
||||
}
|
||||
btn.disabled = true; resetBusy = true;
|
||||
try {
|
||||
const r = await fetch(API + '/api/password-reset/request', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({email: email})
|
||||
});
|
||||
if (!r.ok) { // 429 при частых попытках, 5xx при аварии — не выдаём за успех
|
||||
showBox('reset-error', await serverReason(r, 'Не удалось отправить письмо. Попробуйте позже.'));
|
||||
return false;
|
||||
}
|
||||
// Ответ одинаков и для незнакомой почты: по нему нельзя перебирать учётки.
|
||||
document.getElementById('reset-sent-to').textContent =
|
||||
'Если такая учётка есть, письмо с кодом ушло на ' + email + '. Код действует 15 минут.';
|
||||
document.getElementById('reset-step-1').style.display = 'none';
|
||||
document.getElementById('reset-step-2').style.display = '';
|
||||
document.getElementById('reset-code').focus();
|
||||
} catch {
|
||||
showBox('reset-error', 'Не получилось связаться с сервером. Попробуйте ещё раз.');
|
||||
} finally { btn.disabled = false; resetBusy = false; }
|
||||
return false;
|
||||
}
|
||||
const code = document.getElementById('reset-code').value.trim();
|
||||
const pass = document.getElementById('reset-pass').value;
|
||||
if (!code || pass.length < 6) {
|
||||
showBox('reset-error', 'Введите код из письма и новый пароль не короче шести знаков');
|
||||
return false;
|
||||
}
|
||||
btn.disabled = true; resetBusy = true;
|
||||
try {
|
||||
const r = await fetch(API + '/api/password-reset/confirm', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({email: email, code: code, password: pass})
|
||||
});
|
||||
if (!r.ok) {
|
||||
showBox('reset-error', await serverReason(r, 'Код неверен или просрочен. Запросите новый.'));
|
||||
return false;
|
||||
}
|
||||
closeReset();
|
||||
document.getElementById('login-user').value = email;
|
||||
document.getElementById('login-pass').value = '';
|
||||
showBox('login-notice', 'Пароль изменён. Войдите с новым паролем.');
|
||||
document.getElementById('login-pass').focus();
|
||||
} catch {
|
||||
showBox('reset-error', 'Не получилось связаться с сервером. Попробуйте ещё раз.');
|
||||
} finally { btn.disabled = false; resetBusy = false; }
|
||||
return false;
|
||||
}
|
||||
async function tryRefreshToken() {
|
||||
const rt = localStorage.getItem('refresh_token');
|
||||
if (!rt) return false;
|
||||
|
||||
Reference in New Issue
Block a user