astro_avtourist/frontend/src/pages/api/auth/sign-up.ts

75 lines
No EOL
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { APIRoute } from 'astro';
import { pb } from '../../../lib/pb';
import { sendEmail, generateVerifyEmailHtml, getSiteUrl } from '../../../lib/email';
export const POST: APIRoute = async ({ request, redirect }) => {
try {
const data = await request.json();
console.log('Registration attempt:', { email: data.email, firstName: data.firstName, lastName: data.lastName });
const { firstName, lastName, email, phone, password } = data;
if (!firstName || !lastName || !email || !password) {
return new Response(JSON.stringify({
success: false,
error: 'Все поля обязательны'
}), { status: 400 });
}
// Создаём пользователя
const record = await pb.collection('users').create({
firstName,
lastName,
email,
phone,
password,
passwordConfirm: password,
emailVisibility: true,
});
console.log('User created:', record.id);
// Создаём токен подтверждения
const verifyToken = Buffer.from(`${record.id}:${email}:${Date.now()}`).toString('base64').replace(/=/g, '');
const verifyLink = `${getSiteUrl()}/auth/verify?token=${verifyToken}&userId=${record.id}`;
// Отправляем письмо с ссылкой подтверждения
const html = generateVerifyEmailHtml(firstName || 'Пользователь', verifyLink);
const emailSent = await sendEmail({
to: email,
subject: 'Подтверждение регистрации — Автоюрист Сургут',
html
});
console.log('Verify email sent:', emailSent);
return new Response(JSON.stringify({
success: true,
message: 'На ваш email отправлена ссылка для подтверждения регистрации',
email
}), { status: 201 });
} catch (error: any) {
console.error('Sign up error:', error);
let errorMessage = 'Ошибка при регистрации';
if (error.response?.data) {
const data = error.response.data;
if (data.email) {
errorMessage = `Email: ${data.email.message || 'уже используется'}`;
} else if (data.password) {
errorMessage = `Пароль: ${data.password.message || 'некорректный'}`;
}
} else if (error.message) {
errorMessage = error.message;
}
return new Response(JSON.stringify({
success: false,
error: errorMessage
}), { status: 400 });
}
};