From e84dd414bd9276a884132d047bbc75a8dcab351b Mon Sep 17 00:00:00 2001 From: Web-serfer Date: Mon, 27 Apr 2026 21:29:12 +0500 Subject: [PATCH] Refactor: remove superuser auth from reset-password and confirm --- frontend/src/pages/api/auth/confirm.ts | 51 +++---------------- frontend/src/pages/api/auth/reset-password.ts | 46 +++-------------- 2 files changed, 16 insertions(+), 81 deletions(-) diff --git a/frontend/src/pages/api/auth/confirm.ts b/frontend/src/pages/api/auth/confirm.ts index bf8a8d2..fbb87a1 100644 --- a/frontend/src/pages/api/auth/confirm.ts +++ b/frontend/src/pages/api/auth/confirm.ts @@ -1,15 +1,12 @@ import type { APIRoute } from 'astro'; -import PocketBase from 'pocketbase'; + +const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090'; export const POST: APIRoute = async ({ request }) => { try { - const pb = new PocketBase(import.meta.env.POCKETBASE_URL); const data = await request.json(); - const { token, userId } = data; - console.log('Confirm request:', { userId, token }); - if (!token || !userId) { return new Response(JSON.stringify({ success: false, @@ -17,7 +14,6 @@ export const POST: APIRoute = async ({ request }) => { }), { status: 400 }); } - // Декодируем токен const decoded = Buffer.from(token, 'base64').toString('utf8'); const parts = decoded.split(':'); @@ -30,7 +26,6 @@ export const POST: APIRoute = async ({ request }) => { const [tokenUserId, email, timestamp] = parts; - // Проверяем что userId совпадает if (tokenUserId !== userId) { return new Response(JSON.stringify({ success: false, @@ -38,7 +33,6 @@ export const POST: APIRoute = async ({ request }) => { }), { status: 400 }); } - // Проверяем срок токена (24 часа) const tokenTime = parseInt(timestamp); const now = Date.now(); const maxAge = 24 * 60 * 60 * 1000; @@ -50,50 +44,21 @@ export const POST: APIRoute = async ({ request }) => { }), { status: 400 }); } - // Обновляем пользователя через HTTP с аутентификацией супер-админа - 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; - console.log('Superuser authenticated'); - } else { - console.error('Auth failed:', authResponse.status); - return new Response(JSON.stringify({ - success: false, - error: 'Ошибка аутентификации' - }), { status: 400 }); - } - - // Обновляем - const updateResponse = await fetch(`${import.meta.env.POCKETBASE_URL}/api/collections/users/records/${userId}`, { + const response = await fetch(`${POCKETBASE_URL}/api/collections/users/records/${userId}`, { method: 'PATCH', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${authToken}`, - }, + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ verified: true }), }); - if (!updateResponse.ok) { - const err = await updateResponse.json(); - console.error('Update error:', err); + if (!response.ok) { + const err = await response.json(); + console.error('Verify error:', err); return new Response(JSON.stringify({ success: false, - error: 'Не удалось обновить пользователя' + error: 'Не удалось подтвердить email' }), { status: 400 }); } - console.log('User verified:', userId); - return new Response(JSON.stringify({ success: true, message: 'Email подтверждён' diff --git a/frontend/src/pages/api/auth/reset-password.ts b/frontend/src/pages/api/auth/reset-password.ts index cd4baef..df4da11 100644 --- a/frontend/src/pages/api/auth/reset-password.ts +++ b/frontend/src/pages/api/auth/reset-password.ts @@ -1,14 +1,12 @@ import type { APIRoute } from 'astro'; -import { pb } from '../../../lib/pb'; + +const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090'; export const POST: APIRoute = async ({ request }) => { try { 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, @@ -16,7 +14,6 @@ export const POST: APIRoute = async ({ request }) => { }), { status: 400 }); } - // Валидация токена const decoded = Buffer.from(token, 'base64').toString('utf8'); const [tokenUserId, timestamp] = decoded.split(':'); @@ -27,7 +24,6 @@ export const POST: APIRoute = async ({ request }) => { }), { status: 400 }); } - // Проверяем срок (1 час) const tokenTime = parseInt(timestamp); const now = Date.now(); const maxAge = 60 * 60 * 1000; @@ -39,51 +35,25 @@ export const POST: APIRoute = async ({ request }) => { }), { status: 400 }); } - // Аутентификация как superuser - const authResponse = await fetch(`${import.meta.env.POCKETBASE_URL}/api/collections/_superusers/auth-with-password`, { + const response = await fetch(`${POCKETBASE_URL}/api/collections/users/confirm-password-reset`, { 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({ + token: token, password: password, passwordConfirm: password, }), }); - if (!updateResponse.ok) { - const err = await updateResponse.json(); - console.error('Update password error:', err); + if (!response.ok) { + const err = await response.json(); + console.error('Reset password error:', err); return new Response(JSON.stringify({ success: false, - error: 'Не удалось обновить пароль' + error: 'Не удалось сбросить пароль' }), { status: 400 }); } - console.log('Password updated for:', userId); - return new Response(JSON.stringify({ success: true, message: 'Пароль успешно изменён'