astro_avtourist/frontend/src/pages/api/auth/reset-password.ts

70 lines
No EOL
2.1 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';
const PB_POCKETBASE_URL = import.meta.env.PB_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;
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 });
}
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 });
}
const response = await fetch(`${PB_POCKETBASE_URL}/api/collections/users/confirm-password-reset`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: token,
password: password,
passwordConfirm: password,
}),
});
if (!response.ok) {
const err = await response.json();
console.error('Reset password error:', err);
return new Response(JSON.stringify({
success: false,
error: 'Не удалось сбросить пароль'
}), { status: 400 });
}
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 });
}
};