Создана кнопка выхода из системы
This commit is contained in:
parent
229826acc3
commit
261d5db2d7
13 changed files with 1244 additions and 12 deletions
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 });
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue