artable/src/pages/userapi/deleteUser.ts

46 lines
1.6 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 { APIContext } from "astro";
import { deleteUser, getSessionUser } from "../../db";
import { Prisma } from "@prisma/client";
export async function post({ request, cookies }: APIContext) {
const response: { ok: boolean; reason?: string } = {
ok: true,
};
try {
const sessId = cookies.get("session").value!;
const user = (await getSessionUser(sessId))!;
if (!user.is_admin) {
throw new Error("Доступно только администраторам");
}
const formData = await request.formData();
const login = formData.get("login");
if (login === null) {
throw new Error("Не предоставлены данные для удаления пользователя");
}
if (login.toString() === user.login) {
throw new Error("Невозможно удалить самого себя");
}
const deletedUser = await deleteUser(login.toString());
if (deletedUser === null) {
throw new Error("Не удалось удалить пользователя");
}
response.ok = true;
} catch (e: any) {
response.ok = false;
if (e instanceof Prisma.PrismaClientKnownRequestError) {
response.reason = `Неизвестная ошибка базы данных. Код ${e.code}`;
} else if (e instanceof Error) {
response.reason = e.message.trim();
} else {
response.reason = e.toString().trim();
}
}
return {
body: JSON.stringify(response),
};
}