Создана кнопка выхода из системы

This commit is contained in:
Web-serfer 2026-04-15 19:04:27 +05:00
parent 229826acc3
commit 261d5db2d7
13 changed files with 1244 additions and 12 deletions

View file

@ -2,6 +2,8 @@
import Logo from "./Logo.astro";
import Navbar from "./Navbar.astro";
import MobileMenu from "./MobileMenu.astro";
import LoginButton from "./LoginButton.astro";
import UserMenu from "./UserMenu.astro";
import { COMPANY } from "@constants";
---
@ -20,10 +22,11 @@ import { COMPANY } from "@constants";
<Navbar />
</div>
<!-- Phone -->
<!-- Right side -->
<div class="header-column header-right animate-load" data-delay="200">
<div class="header-actions">
<a href={`tel:${COMPANY.phoneClean}`} class="header-phone">
<div class="header-actions" id="auth-section"></div>
<a href={`tel:${COMPANY.phoneClean}`} class="header-phone" id="header-phone">
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
@ -331,8 +334,120 @@ import { COMPANY } from "@constants";
</style>
<script>
// Анимация при загрузке страницы
// Проверка авторизации и отображение правильного меню
function initAuth() {
const authSection = document.getElementById('auth-section');
const phoneEl = document.getElementById('header-phone');
if (!authSection) return;
const token = localStorage.getItem('auth_token');
const userData = localStorage.getItem('user');
if (token && userData) {
try {
const user = JSON.parse(userData);
const firstLetter = (user.name || user.email || 'U').charAt(0).toUpperCase();
// Скрываем телефон, показываем аватар и кнопку выхода
if (phoneEl) phoneEl.style.display = 'none';
authSection.innerHTML = `
<div class="user-display">
<div class="user-avatar" title="${user.name || user.email}">${firstLetter}</div>
<button class="logout-btn" id="logout-btn" title="Выйти">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
</button>
</div>
`;
// Обработчик выхода
document.getElementById('logout-btn')?.addEventListener('click', async () => {
try {
await fetch('/api/auth/logout', { method: 'POST' });
} catch (e) {}
localStorage.removeItem('auth_token');
localStorage.removeItem('user');
window.location.href = '/';
});
} catch (e) {
showPhone();
}
} else {
showPhone();
}
}
function showPhone() {
const authSection = document.getElementById('auth-section');
const phoneEl = document.getElementById('header-phone');
if (phoneEl) phoneEl.style.display = 'flex';
if (authSection) authSection.innerHTML = '';
}
// Стили
const authStyle = `
.user-display {
display: flex;
align-items: center;
gap: 0.5rem;
}
.user-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
font-size: 0.9rem;
}
.logout-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
background: #ef4444;
border: none;
border-radius: 8px;
color: #fff;
cursor: pointer;
transition: all 0.3s ease;
}
.logout-btn:hover {
background: #dc2626;
transform: scale(1.05);
}
@media (max-width: 992px) {
.user-avatar {
width: 32px;
height: 32px;
font-size: 0.8rem;
}
.logout-btn {
width: 32px;
height: 32px;
}
.logout-btn svg {
width: 16px;
height: 16px;
}
}
`;
document.addEventListener("DOMContentLoaded", () => {
const styleEl = document.createElement('style');
styleEl.textContent = authStyle;
document.head.appendChild(styleEl);
initAuth();
const animatedElements = document.querySelectorAll(".animate-load");
animatedElements.forEach((el) => {

View file

@ -0,0 +1,118 @@
---
export interface Props {
userName?: string;
userEmail?: string;
class?: string;
}
const {
userName = '',
userEmail = '',
class: className = '',
}: Props = Astro.props;
// Получаем первую букву имени
const firstLetter = userName ? userName.charAt(0).toUpperCase() : userEmail?.charAt(0).toUpperCase() || 'U';
---
<div class={`user-menu ${className}`}>
<div class="user-avatar" title={userName || userEmail}>
{firstLetter}
</div>
<button class="logout-btn" id="logout-btn" title="Выйти">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
<span class="logout-text">Выход</span>
</button>
</div>
<style>
.user-menu {
display: flex;
align-items: center;
gap: 0.75rem;
}
.user-avatar {
width: 42px;
height: 42px;
border-radius: 50%;
background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%);
color: #ffffff;
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
font-size: 1.1rem;
cursor: default;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.user-avatar:hover {
transform: scale(1.05);
box-shadow: 0 4px 12px rgba(206, 159, 64, 0.4);
}
.logout-btn {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.6rem 1rem;
background: transparent;
border: 2px solid #1e3050;
border-radius: 8px;
color: #1e3050;
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.3s ease;
}
.logout-btn:hover {
background: #1e3050;
color: #ffffff;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.logout-btn:active {
transform: translateY(0);
}
@media (max-width: 992px) {
.logout-text {
display: none;
}
.logout-btn {
padding: 0.6rem;
}
}
</style>
<script>
document.addEventListener('DOMContentLoaded', () => {
const logoutBtn = document.getElementById('logout-btn');
logoutBtn?.addEventListener('click', async () => {
try {
await fetch('/api/auth/logout', {
method: 'POST',
});
} catch (e) {
console.error('Logout error:', e);
}
// Очищаем localStorage
localStorage.removeItem('auth_token');
localStorage.removeItem('user');
// Перенаправляем на главную
window.location.href = '/';
});
});
</script>

View file

@ -0,0 +1,123 @@
import type { APIRoute } from 'astro';
import PocketBase from 'pocketbase';
import { sendEmail, getSiteUrl } from '../../../lib/email';
function generateResetPasswordHtml(firstName: string, resetLink: string): string {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Сброс пароля</title>
</head>
<body style="margin: 0; padding: 0; background-color: #f5f7fa; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f5f7fa; padding: 40px 20px;">
<tr>
<td align="center">
<table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08);">
<tr>
<td style="background: linear-gradient(135deg, #1e3050 0%, #2d4a6f 100%); padding: 30px 40px; text-align: center;">
<h1 style="color: #ffffff; margin: 0; font-size: 28px; font-weight: 700;">Автоюрист Сургут</h1>
<p style="color: rgba(255,255,255,0.8); margin: 10px 0 0 0; font-size: 16px;">Юридические услуги для автовладельцев</p>
</td>
</tr>
<tr>
<td style="padding: 40px;">
<h2 style="color: #1e3050; margin: 0 0 20px 0; font-size: 24px; font-weight: 700;">Сброс пароля</h2>
<p style="color: #64748b; font-size: 16px; line-height: 1.6; margin: 0 0 20px 0;">
Здравствуйте, ${firstName}!
</p>
<p style="color: #64748b; font-size: 16px; line-height: 1.6; margin: 0 0 30px 0;">
Вы запросили сброс пароля. Нажмите кнопку ниже для создания нового пароля:
</p>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<a href="${resetLink}" style="display: inline-block; background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%); color: #ffffff; text-decoration: none; padding: 16px 32px; border-radius: 8px; font-size: 16px; font-weight: 700;">
Сбросить пароль
</a>
</td>
</tr>
</table>
<p style="color: #94a3b8; font-size: 14px; margin: 30px 0 0 0;">
Ссылка действительна 1 час. Если вы не запрашивали сброс пароля, просто проигнорируйте это письмо.
</p>
</td>
</tr>
<tr>
<td style="background-color: #1e3050; padding: 24px 40px; text-align: center;">
<p style="color: rgba(255,255,255,0.6); font-size: 14px; margin: 0;">
© 2026 Автоюрист Сургут. Все права защищены.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
}
export const POST: APIRoute = async ({ request }) => {
try {
const pb = new PocketBase(import.meta.env.POCKETBASE_URL);
const data = await request.json();
const { email } = data;
console.log('Password reset request:', email);
if (!email) {
return new Response(JSON.stringify({
success: false,
error: 'Email обязателен'
}), { status: 400 });
}
// Проверяем существует ли пользователь
let user = null;
try {
user = await pb.collection('users').getFirstListItem(`email="${email}"`);
} catch (e) {
console.log('User not found, still return success');
}
if (!user) {
return new Response(JSON.stringify({
success: true,
message: 'Ссылка для сброса пароля отправлена'
}), { status: 200 });
}
// Создаём свой токен сброса (как для верификации)
const resetToken = Buffer.from(`${user.id}:${Date.now()}`).toString('base64').replace(/=/g, '');
const resetLink = `${getSiteUrl()}/auth/reset-password?token=${resetToken}&userId=${user.id}`;
// Отправляем письмо
const firstName = user.firstName || 'Пользователь';
const html = generateResetPasswordHtml(firstName, resetLink);
const emailSent = await sendEmail({
to: email,
subject: 'Сброс пароля — Автоюрист Сургут',
html
});
console.log('Reset email sent:', emailSent);
return new Response(JSON.stringify({
success: true,
message: 'Ссылка для сброса пароля отправлена'
}), { status: 200 });
} catch (error: any) {
console.error('Forgot password error:', error);
return new Response(JSON.stringify({
success: true,
message: 'Ссылка для сброса пароля отправлена'
}), { status: 200 });
}
};

View file

@ -0,0 +1,11 @@
import type { APIRoute } from 'astro';
export const POST: APIRoute = async ({ cookies }) => {
// Очищаем куку авторизации
cookies.delete('pb_auth', { path: '/' });
return new Response(JSON.stringify({
success: true,
message: 'Вышли из аккаунта'
}), { status: 200 });
};

View file

@ -0,0 +1,101 @@
import type { APIRoute } from 'astro';
import PocketBase from 'pocketbase';
export const POST: APIRoute = async ({ request }) => {
try {
const pb = new PocketBase(import.meta.env.POCKETBASE_URL);
const data = await request.json();
const { token, userId, password } = data;
console.log('Reset password request:', { userId });
if (!token || !userId || !password) {
return new Response(JSON.stringify({
success: false,
error: 'Отсутствуют параметры'
}), { status: 400 });
}
// Валидация токена
const decoded = Buffer.from(token, 'base64').toString('utf8');
const [tokenUserId, timestamp] = decoded.split(':');
if (tokenUserId !== userId) {
return new Response(JSON.stringify({
success: false,
error: 'Неверный токен'
}), { status: 400 });
}
// Проверяем срок (1 час)
const tokenTime = parseInt(timestamp);
const now = Date.now();
const maxAge = 60 * 60 * 1000;
if (now - tokenTime > maxAge) {
return new Response(JSON.stringify({
success: false,
error: 'Срок действия ссылки истёк'
}), { status: 400 });
}
// Аутентификация как superuser
const authResponse = await fetch(`${import.meta.env.POCKETBASE_URL}/api/collections/_superusers/auth-with-password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
identity: import.meta.env.PB_ADMIN_EMAIL,
password: import.meta.env.PB_ADMIN_PASSWORD,
}),
});
let authToken = '';
if (authResponse.ok) {
const authData = await authResponse.json();
authToken = authData.token;
} else {
return new Response(JSON.stringify({
success: false,
error: 'Ошибка аутентификации'
}), { status: 400 });
}
// Обновляем пароль
const updateResponse = await fetch(`${import.meta.env.POCKETBASE_URL}/api/collections/users/records/${userId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`,
},
body: JSON.stringify({
password: password,
passwordConfirm: password,
}),
});
if (!updateResponse.ok) {
const err = await updateResponse.json();
console.error('Update password error:', err);
return new Response(JSON.stringify({
success: false,
error: 'Не удалось обновить пароль'
}), { status: 400 });
}
console.log('Password updated for:', userId);
return new Response(JSON.stringify({
success: true,
message: 'Пароль успешно изменён'
}), { status: 200 });
} catch (error: any) {
console.error('Reset password error:', error);
return new Response(JSON.stringify({
success: false,
error: 'Ошибка при сбросе пароля'
}), { status: 400 });
}
};

View file

@ -15,7 +15,19 @@ export const POST: APIRoute = async ({ request, cookies }) => {
}), { status: 400 });
}
const authRecord = await pb.collection('users').authWithPassword(email, password);
const authData = await pb.collection('users').authWithPassword(email, password);
console.log('Auth data token:', authData.token ? 'yes' : 'no');
console.log('Auth record id:', authData.record?.id);
console.log('Auth record verified:', authData.record?.verified);
// Проверяем верификацию
if (!authData.record.verified) {
return new Response(JSON.stringify({
success: false,
error: 'Email не подтверждён'
}), { status: 401 });
}
cookies.set('pb_auth', JSON.stringify(pb.authStore.exportToCookie()), {
path: '/',
@ -27,10 +39,11 @@ export const POST: APIRoute = async ({ request, cookies }) => {
return new Response(JSON.stringify({
success: true,
token: authData.token,
user: {
id: authRecord.id,
name: authRecord.name,
email: authRecord.email,
id: authData.record.id,
name: authData.record.name || authData.record.firstName,
email: authData.record.email,
}
}), { status: 200 });

View file

@ -11,10 +11,10 @@ export const POST: APIRoute = async ({ request, redirect }) => {
const { firstName, lastName, email, phone, password } = data;
if (!email || !password) {
if (!firstName || !lastName || !email || !password) {
return new Response(JSON.stringify({
success: false,
error: 'Email и пароль обязательны'
error: 'Все поля обязательны'
}), { status: 400 });
}
@ -36,7 +36,7 @@ export const POST: APIRoute = async ({ request, redirect }) => {
const verifyLink = `${getSiteUrl()}/auth/verify?token=${verifyToken}&userId=${record.id}`;
// Отправляем письмо с ссылкой подтверждения
const html = generateVerifyEmailHtml(firstName || lastName || 'Пользователь', verifyLink);
const html = generateVerifyEmailHtml(firstName || 'Пользователь', verifyLink);
const emailSent = await sendEmail({
to: email,

View file

@ -0,0 +1,250 @@
---
import Layout from '@layouts/Layout.astro';
import { SITE_URL } from '@constants';
---
<Layout
title="Восстановление пароля"
description="Восстановите доступ к аккаунту"
canonicalLink={`${SITE_URL}/auth/forgot-password`}
>
<div class="auth-page">
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<h1>Восстановление пароля</h1>
<p>Введите email для сброса пароля</p>
</div>
<form class="auth-form" id="forgot-form">
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="example@mail.ru"
required
autocomplete="email"
inputmode="email"
/>
<span class="error-message" id="email-error"></span>
</div>
<button type="submit" class="btn-submit" id="submit-btn">
Отправить ссылку
</button>
</form>
<div class="auth-messages">
<div class="success-message hidden" id="success-message">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
<polyline points="22 4 12 14.01 9 11.01"></polyline>
</svg>
<p>На ваш email отправлена ссылка для сброса пароля</p>
</div>
<div class="error-message hidden" id="form-error"></div>
</div>
<div class="auth-footer">
<p>Вспомнили пароль? <a href="/auth/sign-in">Войти</a></p>
</div>
</div>
</div>
</div>
</Layout>
<script>
const form = document.getElementById('forgot-form') as HTMLFormElement;
const emailInput = document.getElementById('email') as HTMLInputElement;
const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement;
const successMessage = document.getElementById('success-message');
const formError = document.getElementById('form-error');
form?.addEventListener('submit', async (e) => {
e.preventDefault();
const email = emailInput.value.trim();
if (!email) return;
submitBtn.disabled = true;
submitBtn.textContent = 'Отправка...';
try {
const response = await fetch('/api/auth/forgot-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
const data = await response.json();
if (response.ok && data.success) {
form.classList.add('hidden');
successMessage?.classList.remove('hidden');
} else {
const errorEl = document.getElementById('email-error');
if (errorEl) errorEl.textContent = data.error || 'Ошибка';
}
} catch (err) {
if (formError) {
formError.textContent = 'Ошибка соединения';
formError.classList.remove('hidden');
}
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Отправить ссылку';
}
});
</script>
<style>
.auth-page {
min-height: calc(100vh - 160px);
background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 6rem 2rem 2rem;
}
.auth-container {
width: 100%;
max-width: 440px;
}
.auth-card {
background: #ffffff;
border-radius: 16px;
padding: 2rem;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}
.auth-header {
text-align: center;
margin-bottom: 2rem;
}
.auth-header h1 {
color: #1e3050;
font-size: 1.5rem;
font-weight: 700;
margin: 0 0 0.5rem;
}
.auth-header p {
color: #64748b;
font-size: 0.95rem;
margin: 0;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
color: #1e3050;
font-size: 0.875rem;
font-weight: 600;
margin-bottom: 0.5rem;
}
.form-group input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #e2e8f0;
border-radius: 8px;
font-size: 0.95rem;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-group input:focus {
outline: none;
border-color: #eac26e;
box-shadow: 0 0 0 3px rgba(234, 194, 110, 0.2);
}
.error-message {
color: #ef4444;
font-size: 0.8rem;
margin-top: 0.25rem;
display: block;
}
.btn-submit {
width: 100%;
padding: 0.875rem;
background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%);
color: #ffffff;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 700;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
}
.btn-submit:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(206, 159, 64, 0.4);
}
.btn-submit:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.auth-messages {
margin-top: 1.5rem;
text-align: center;
}
.success-message {
display: flex;
align-items: center;
gap: 0.75rem;
color: #10b981;
padding: 1rem;
background: #ecfdf5;
border-radius: 8px;
}
.success-message svg {
flex-shrink: 0;
}
.success-message p {
margin: 0;
font-size: 0.95rem;
}
.auth-footer {
margin-top: 1.5rem;
text-align: center;
padding-top: 1.5rem;
border-top: 1px solid #e2e8f0;
}
.auth-footer p {
color: #64748b;
font-size: 0.9rem;
margin: 0;
}
.auth-footer a {
color: #eac26e;
text-decoration: none;
font-weight: 600;
}
.auth-footer a:hover {
text-decoration: underline;
}
.hidden {
display: none !important;
}
</style>

View file

@ -0,0 +1,361 @@
---
import Layout from '@layouts/Layout.astro';
import { SITE_URL } from '@constants';
const token = Astro.url.searchParams.get('token');
const userId = Astro.url.searchParams.get('userId');
const error = Astro.url.searchParams.get('error');
---
<Layout
title="Сброс пароля"
description="Создайте новый пароль"
canonicalLink={`${SITE_URL}/auth/reset-password`}
>
<div class="auth-page">
<div class="auth-container">
<div class="auth-card" id="card">
<!-- Форма сброса пароля -->
<div id="reset-form-container">
<div class="auth-header">
<h1>Новый пароль</h1>
<p>Придумайте новый пароль для аккаунта</p>
</div>
<form class="auth-form" id="reset-form">
<input type="hidden" name="userId" id="userId" value={userId} />
<input type="hidden" name="token" id="token" value={token} />
<div class="form-group">
<label for="password">
Новый пароль
<span class="hint">От 8 до 12 символов</span>
</label>
<div class="password-wrapper">
<input
type="password"
id="password"
name="password"
placeholder="••••••••"
required
minlength="8"
maxlength="12"
/>
<button type="button" class="toggle-password" data-target="password">
<svg class="eye-open" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
<circle cx="12" cy="12" r="3"></circle>
</svg>
<svg class="eye-closed" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
<line x1="1" y1="1" x2="23" y2="23"></line>
</svg>
</button>
</div>
<span class="error-message" id="password-error"></span>
</div>
<div class="form-group">
<label for="confirmPassword">Подтвердите пароль</label>
<input
type="password"
id="confirmPassword"
name="confirmPassword"
placeholder="••••••••"
required
minlength="8"
maxlength="12"
/>
<span class="error-message" id="confirm-error"></span>
</div>
<button type="submit" class="btn-submit" id="submit-btn">
Сохранить пароль
</button>
</form>
</div>
<!-- Успех -->
<div id="success-container" class="hidden">
<div class="auth-header">
<div class="success-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
<polyline points="22 4 12 14.01 9 11.01"></polyline>
</svg>
</div>
<h1>Пароль изменён!</h1>
<p>Теперь вы можете войти с новым паролем</p>
</div>
<a href="/auth/sign-in" class="btn-submit">Войти</a>
</div>
<!-- Ошибка -->
<div id="error-container" class="hidden">
<div class="auth-header">
<div class="error-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<line x1="15" y1="9" x2="9" y2="15"></line>
<line x1="9" y1="9" x2="15" y2="15"></line>
</svg>
</div>
<h1>Ошибка</h1>
<p id="error-text">Ссылка недействительна или истёк срок действия</p>
</div>
<a href="/auth/forgot-password" class="btn-submit">Запросить заново</a>
</div>
</div>
</div>
</div>
</Layout>
<script>
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
const userId = urlParams.get('userId');
const error = urlParams.get('error');
const form = document.getElementById('reset-form') as HTMLFormElement;
const card = document.getElementById('card');
const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement;
// Показ секций
function showSection(id: string) {
const formContainer = document.getElementById('reset-form-container');
const successContainer = document.getElementById('success-container');
const errorContainer = document.getElementById('error-container');
formContainer?.classList.add('hidden');
successContainer?.classList.add('hidden');
errorContainer?.classList.add('hidden');
document.getElementById(id)?.classList.remove('hidden');
}
// Обработка формы
form?.addEventListener('submit', async (e) => {
e.preventDefault();
const password = (document.getElementById('password') as HTMLInputElement).value;
const confirmPassword = (document.getElementById('confirmPassword') as HTMLInputElement).value;
// Валидация
if (password !== confirmPassword) {
const errorEl = document.getElementById('confirm-error');
if (errorEl) errorEl.textContent = 'Пароли не совпадают';
return;
}
if (password.length < 8 || password.length > 12) {
const errorEl = document.getElementById('password-error');
if (errorEl) errorEl.textContent = 'Пароль должен быть от 8 до 12 символов';
return;
}
submitBtn.disabled = true;
submitBtn.textContent = 'Сохранение...';
try {
const response = await fetch('/api/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, userId, password }),
});
const data = await response.json();
if (response.ok && data.success) {
showSection('success-container');
} else {
const errorEl = document.getElementById('password-error');
if (errorEl) errorEl.textContent = data.error || 'Ошибка';
}
} catch (err) {
const errorEl = document.getElementById('password-error');
if (errorEl) errorEl.textContent = 'Ошибка соединения';
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Сохранить пароль';
}
});
// Переключение видимости пароля
document.querySelectorAll('.toggle-password').forEach(btn => {
btn.addEventListener('click', () => {
const target = (btn as HTMLButtonElement).dataset.target;
const input = document.getElementById(target || '') as HTMLInputElement;
if (input) {
input.type = input.type === 'password' ? 'text' : 'password';
}
});
});
// Инициализация
if (error) {
const errorText = document.getElementById('error-text');
if (errorText) errorText.textContent = error;
showSection('error-container');
} else if (!token || !userId) {
showSection('error-container');
}
</script>
<style>
.auth-page {
min-height: calc(100vh - 160px);
background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 6rem 2rem 2rem;
}
.auth-container {
width: 100%;
max-width: 440px;
}
.auth-card {
background: #ffffff;
border-radius: 16px;
padding: 2rem;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}
.auth-header {
text-align: center;
margin-bottom: 2rem;
}
.auth-header h1 {
color: #1e3050;
font-size: 1.5rem;
font-weight: 700;
margin: 1rem 0 0.5rem;
}
.auth-header p {
color: #64748b;
font-size: 0.95rem;
margin: 0;
}
.success-icon, .error-icon {
width: 80px;
height: 80px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
}
.success-icon {
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}
.error-icon {
background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
}
.success-icon svg, .error-icon svg {
color: white;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
color: #1e3050;
font-size: 0.875rem;
font-weight: 600;
margin-bottom: 0.5rem;
}
.form-group .hint {
color: #94a3b8;
font-weight: 400;
margin-left: 0.5rem;
}
.form-group input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #e2e8f0;
border-radius: 8px;
font-size: 0.95rem;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-group input:focus {
outline: none;
border-color: #eac26e;
box-shadow: 0 0 0 3px rgba(234, 194, 110, 0.2);
}
.password-wrapper {
position: relative;
}
.password-wrapper input {
padding-right: 3rem;
}
.toggle-password {
position: absolute;
right: 0.75rem;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
cursor: pointer;
color: #94a3b8;
}
.toggle-password .eye-closed {
display: none;
}
.password-wrapper input[type="text"] + .toggle-password .eye-open,
.password-wrapper input[type="text"] + .toggle-password .eye-closed {
display: none;
}
.password-wrapper input[type="text"] + .toggle-password .eye-closed {
display: block;
}
.error-message {
color: #ef4444;
font-size: 0.8rem;
margin-top: 0.25rem;
display: block;
}
.btn-submit {
width: 100%;
padding: 0.875rem;
background: linear-gradient(135deg, #eac26e 0%, #ce9f40 100%);
color: #ffffff;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 700;
cursor: pointer;
text-decoration: none;
display: inline-block;
text-align: center;
transition: transform 0.2s, box-shadow 0.2s;
}
.btn-submit:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(206, 159, 64, 0.4);
}
.hidden {
display: none !important;
}
</style>

View file

@ -77,7 +77,7 @@ import { SITE_URL } from '@constants';
<input type="checkbox" name="remember" />
<span>Запомнить меня</span>
</label>
<a href="#" class="forgot-link">Забыли пароль?</a>
<a href="/auth/forgot-password" class="forgot-link">Забыли пароль?</a>
</div>
<button type="submit" class="btn-submit">
@ -447,5 +447,39 @@ import { SITE_URL } from '@constants';
}
console.log('Вход:', { email, password });
const submitBtn = document.querySelector('.btn-submit') as HTMLButtonElement;
submitBtn.disabled = true;
submitBtn.textContent = 'Вход...';
try {
const response = await fetch('/api/auth/sign-in', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (response.ok && data.token) {
// Сохраняем токен
localStorage.setItem('auth_token', data.token);
localStorage.setItem('user', JSON.stringify(data.user));
// Перенаправляем в личный кабинет
window.location.href = '/cabinet';
} else if (data.error?.includes('подтверждён')) {
showError(emailInput, data.error);
} else if (data.error?.includes('пароль')) {
showError(passwordInput, data.error);
} else {
showError(passwordInput, data.error || 'Неверный email или пароль');
}
} catch (err) {
showError(passwordInput, 'Ошибка соединения');
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Войти';
}
});
</script>