Создана кнопка выхода из системы
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,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue