Refactor: remove superuser auth from reset-password and confirm
This commit is contained in:
parent
7144e27714
commit
e84dd414bd
2 changed files with 16 additions and 81 deletions
|
|
@ -1,15 +1,12 @@
|
||||||
import type { APIRoute } from 'astro';
|
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 }) => {
|
export const POST: APIRoute = async ({ request }) => {
|
||||||
try {
|
try {
|
||||||
const pb = new PocketBase(import.meta.env.POCKETBASE_URL);
|
|
||||||
const data = await request.json();
|
const data = await request.json();
|
||||||
|
|
||||||
const { token, userId } = data;
|
const { token, userId } = data;
|
||||||
|
|
||||||
console.log('Confirm request:', { userId, token });
|
|
||||||
|
|
||||||
if (!token || !userId) {
|
if (!token || !userId) {
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
|
|
@ -17,7 +14,6 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Декодируем токен
|
|
||||||
const decoded = Buffer.from(token, 'base64').toString('utf8');
|
const decoded = Buffer.from(token, 'base64').toString('utf8');
|
||||||
const parts = decoded.split(':');
|
const parts = decoded.split(':');
|
||||||
|
|
||||||
|
|
@ -30,7 +26,6 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
|
|
||||||
const [tokenUserId, email, timestamp] = parts;
|
const [tokenUserId, email, timestamp] = parts;
|
||||||
|
|
||||||
// Проверяем что userId совпадает
|
|
||||||
if (tokenUserId !== userId) {
|
if (tokenUserId !== userId) {
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
|
|
@ -38,7 +33,6 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Проверяем срок токена (24 часа)
|
|
||||||
const tokenTime = parseInt(timestamp);
|
const tokenTime = parseInt(timestamp);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const maxAge = 24 * 60 * 60 * 1000;
|
const maxAge = 24 * 60 * 60 * 1000;
|
||||||
|
|
@ -50,50 +44,21 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Обновляем пользователя через HTTP с аутентификацией супер-админа
|
const response = await fetch(`${POCKETBASE_URL}/api/collections/users/records/${userId}`, {
|
||||||
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}`, {
|
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: {
|
headers: { 'Content-Type': 'application/json' },
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': `Bearer ${authToken}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ verified: true }),
|
body: JSON.stringify({ verified: true }),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!updateResponse.ok) {
|
if (!response.ok) {
|
||||||
const err = await updateResponse.json();
|
const err = await response.json();
|
||||||
console.error('Update error:', err);
|
console.error('Verify error:', err);
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Не удалось обновить пользователя'
|
error: 'Не удалось подтвердить email'
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('User verified:', userId);
|
|
||||||
|
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Email подтверждён'
|
message: 'Email подтверждён'
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,12 @@
|
||||||
import type { APIRoute } from 'astro';
|
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 }) => {
|
export const POST: APIRoute = async ({ request }) => {
|
||||||
try {
|
try {
|
||||||
const data = await request.json();
|
const data = await request.json();
|
||||||
|
|
||||||
const { token, userId, password } = data;
|
const { token, userId, password } = data;
|
||||||
|
|
||||||
console.log('Reset password request:', { userId });
|
|
||||||
|
|
||||||
if (!token || !userId || !password) {
|
if (!token || !userId || !password) {
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
|
|
@ -16,7 +14,6 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Валидация токена
|
|
||||||
const decoded = Buffer.from(token, 'base64').toString('utf8');
|
const decoded = Buffer.from(token, 'base64').toString('utf8');
|
||||||
const [tokenUserId, timestamp] = decoded.split(':');
|
const [tokenUserId, timestamp] = decoded.split(':');
|
||||||
|
|
||||||
|
|
@ -27,7 +24,6 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Проверяем срок (1 час)
|
|
||||||
const tokenTime = parseInt(timestamp);
|
const tokenTime = parseInt(timestamp);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const maxAge = 60 * 60 * 1000;
|
const maxAge = 60 * 60 * 1000;
|
||||||
|
|
@ -39,51 +35,25 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Аутентификация как superuser
|
const response = await fetch(`${POCKETBASE_URL}/api/collections/users/confirm-password-reset`, {
|
||||||
const authResponse = await fetch(`${import.meta.env.POCKETBASE_URL}/api/collections/_superusers/auth-with-password`, {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
identity: import.meta.env.PB_ADMIN_EMAIL,
|
token: token,
|
||||||
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,
|
password: password,
|
||||||
passwordConfirm: password,
|
passwordConfirm: password,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!updateResponse.ok) {
|
if (!response.ok) {
|
||||||
const err = await updateResponse.json();
|
const err = await response.json();
|
||||||
console.error('Update password error:', err);
|
console.error('Reset password error:', err);
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Не удалось обновить пароль'
|
error: 'Не удалось сбросить пароль'
|
||||||
}), { status: 400 });
|
}), { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Password updated for:', userId);
|
|
||||||
|
|
||||||
return new Response(JSON.stringify({
|
return new Response(JSON.stringify({
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Пароль успешно изменён'
|
message: 'Пароль успешно изменён'
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue