ваше сообщение коммита

This commit is contained in:
2025-04-03 14:54:38 +03:00
parent f45fd2715f
commit e05f06c588
2 changed files with 56 additions and 8 deletions

View File

@@ -1169,17 +1169,41 @@ router.post('/email/init', async (req, res) => {
}); });
} }
// Создаем или получаем ID пользователя logger.info(`[email/init] Initializing email authentication for: ${email}`);
// Сохраняем гостевой ID до проверки
const guestId = req.session.guestId;
const previousGuestId = req.session.previousGuestId;
logger.info(`[email/init] Guest context: guestId=${guestId}, previousGuestId=${previousGuestId}`);
// Проверяем, существует ли пользователь с таким email
const existingUserResult = await db.query(
`SELECT u.id FROM users u
JOIN user_identities ui ON u.id = ui.user_id
WHERE ui.provider = $1 AND ui.provider_id = $2`,
['email', email.toLowerCase()]
);
let userId; let userId;
if (req.session.authenticated && req.session.userId) { if (existingUserResult.rows.length > 0) {
// Используем существующего пользователя
userId = existingUserResult.rows[0].id;
logger.info(`[email/init] Found existing user with ID ${userId} for email ${email}`);
} else if (req.session.authenticated && req.session.userId) {
// Используем текущего аутентифицированного пользователя
userId = req.session.userId; userId = req.session.userId;
logger.info(`[email/init] Using current authenticated user with ID ${userId}`);
} else { } else {
// Создаем нового пользователя
const userResult = await db.query( const userResult = await db.query(
'INSERT INTO users (role) VALUES ($1) RETURNING id', 'INSERT INTO users (role) VALUES ($1) RETURNING id',
['user'] ['user']
); );
userId = userResult.rows[0].id; userId = userResult.rows[0].id;
req.session.tempUserId = userId; req.session.tempUserId = userId;
logger.info(`[email/init] Created new user with ID ${userId} for email ${email}`);
} }
// Сохраняем email в сессии // Сохраняем email в сессии

View File

@@ -349,17 +349,27 @@ const clearEmailError = () => {
// Обработчик для Email аутентификации // Обработчик для Email аутентификации
const handleEmailAuth = async () => { const handleEmailAuth = async () => {
try { try {
console.log('Starting email authentication flow');
// Показываем форму для ввода email // Показываем форму для ввода email
showEmailForm.value = true; showEmailForm.value = true;
// Сбрасываем другие состояния форм // Сбрасываем другие состояния форм
showEmailVerification.value = false; showEmailVerification.value = false;
showEmailVerificationInput.value = false; showEmailVerificationInput.value = false;
// Очищаем поля и ошибки // Очищаем поля и ошибки
emailInput.value = ''; emailInput.value = '';
emailFormatError.value = false; emailFormatError.value = false;
emailError.value = ''; emailError.value = '';
console.log('Email form displayed, form states:', {
showEmailForm: showEmailForm.value,
showEmailVerification: showEmailVerification.value,
showEmailVerificationInput: showEmailVerificationInput.value
});
} catch (error) { } catch (error) {
console.error('Error in email auth:', error); console.error('Error initializing email auth:', error);
} }
}; };
@@ -380,6 +390,8 @@ const sendEmailVerification = async () => {
// Отправляем запрос на сервер для инициализации email аутентификации // Отправляем запрос на сервер для инициализации email аутентификации
const response = await axios.post('/api/auth/email/init', { email: emailInput.value }); const response = await axios.post('/api/auth/email/init', { email: emailInput.value });
console.log('Email init response:', response.data);
if (response.data.success) { if (response.data.success) {
// Скрываем форму ввода email // Скрываем форму ввода email
showEmailForm.value = false; showEmailForm.value = false;
@@ -391,12 +403,18 @@ const sendEmailVerification = async () => {
emailVerificationEmail.value = emailInput.value; emailVerificationEmail.value = emailInput.value;
// Очищаем поле для ввода кода // Очищаем поле для ввода кода
emailVerificationCode.value = ''; emailVerificationCode.value = '';
console.log('Showing verification code input form for email:', emailVerificationEmail.value);
} else { } else {
emailError.value = response.data.error || 'Ошибка инициализации аутентификации по email'; emailError.value = response.data.error || 'Ошибка инициализации аутентификации по email';
} }
} catch (error) { } catch (error) {
console.error('Error in email init request:', error);
if (error.response && error.response.data && error.response.data.error) {
emailError.value = error.response.data.error;
} else {
emailError.value = 'Ошибка при запросе кода подтверждения'; emailError.value = 'Ошибка при запросе кода подтверждения';
console.error('Error in email auth:', error); }
} finally { } finally {
isEmailSending.value = false; isEmailSending.value = false;
} }
@@ -416,7 +434,8 @@ const verifyEmailCode = async () => {
// Показываем индикатор процесса верификации // Показываем индикатор процесса верификации
isVerifying.value = true; isVerifying.value = true;
const response = await axios.post('/api/auth/check-email-verification', { const response = await axios.post('/api/auth/email/verify-code', {
email: emailVerificationEmail.value,
code: emailVerificationCode.value code: emailVerificationCode.value
}); });
@@ -446,8 +465,13 @@ const verifyEmailCode = async () => {
emailError.value = response.data.message || 'Неверный код верификации'; emailError.value = response.data.message || 'Неверный код верификации';
} }
} catch (error) { } catch (error) {
if (error.response && error.response.status === 400) {
// Обрабатываем ошибку неверного кода
emailError.value = error.response.data.error || 'Неверный код верификации';
} else {
emailError.value = 'Ошибка при проверке кода'; emailError.value = 'Ошибка при проверке кода';
console.error('Error verifying email code:', error); console.error('Error verifying email code:', error);
}
} finally { } finally {
isVerifying.value = false; isVerifying.value = false;
} }