Создана кнопка выхода из системы
This commit is contained in:
parent
229826acc3
commit
261d5db2d7
13 changed files with 1244 additions and 12 deletions
123
frontend/src/pages/api/auth/forgot-password.ts
Normal file
123
frontend/src/pages/api/auth/forgot-password.ts
Normal 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 });
|
||||
}
|
||||
};
|
||||
11
frontend/src/pages/api/auth/logout.ts
Normal file
11
frontend/src/pages/api/auth/logout.ts
Normal 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 });
|
||||
};
|
||||
101
frontend/src/pages/api/auth/reset-password.ts
Normal file
101
frontend/src/pages/api/auth/reset-password.ts
Normal 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 });
|
||||
}
|
||||
};
|
||||
|
|
@ -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 });
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
250
frontend/src/pages/auth/forgot-password.astro
Normal file
250
frontend/src/pages/auth/forgot-password.astro
Normal 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>
|
||||
361
frontend/src/pages/auth/reset-password.astro
Normal file
361
frontend/src/pages/auth/reset-password.astro
Normal 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>
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue