2025-06-30 18:58:24 +02:00
|
|
|
/*
|
|
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
*/
|
2025-06-24 15:31:47 +02:00
|
|
|
import { readUsers, writeUsers } from "~/server/database";
|
|
|
|
import { apiUserPatchSchema } from "~/shared/types/api";
|
2025-06-23 00:20:33 +02:00
|
|
|
import { z } from "zod/v4-mini";
|
|
|
|
import { broadcastEvent } from "~/server/streams";
|
|
|
|
|
|
|
|
export default defineEventHandler(async (event) => {
|
2025-06-28 00:55:26 +02:00
|
|
|
await requireServerSessionWithAdmin(event);
|
2025-06-23 00:20:33 +02:00
|
|
|
const { success, error, data: patch } = apiUserPatchSchema.safeParse(await readBody(event));
|
|
|
|
if (!success) {
|
|
|
|
throw createError({
|
|
|
|
status: 400,
|
|
|
|
statusText: "Bad Request",
|
|
|
|
message: z.prettifyError(error),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const users = await readUsers();
|
|
|
|
const user = users.find(user => user.id === patch.id);
|
|
|
|
if (!user || user.deleted) {
|
|
|
|
throw createError({
|
|
|
|
status: 409,
|
|
|
|
statusText: "Conflict",
|
|
|
|
message: "User does not exist",
|
|
|
|
});
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
if (patch.type) {
|
|
|
|
if (patch.type === "anonymous" || user.type === "anonymous") {
|
|
|
|
throw createError({
|
|
|
|
status: 409,
|
|
|
|
statusText: "Conflict",
|
|
|
|
message: "Anonymous user type cannot be changed.",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
user.type = patch.type;
|
|
|
|
}
|
|
|
|
if (patch.name) {
|
|
|
|
if (user.type === "anonymous") {
|
|
|
|
throw createError({
|
|
|
|
status: 409,
|
|
|
|
statusText: "Conflict",
|
|
|
|
message: "Anonymous user cannot have name set.",
|
|
|
|
});
|
|
|
|
}
|
|
|
|
user.name = patch.name;
|
|
|
|
}
|
|
|
|
user.updatedAt = new Date().toISOString();
|
|
|
|
await writeUsers(users);
|
|
|
|
broadcastEvent({
|
|
|
|
type: "user-update",
|
|
|
|
data: serverUserToApi(user),
|
|
|
|
})
|
|
|
|
|
|
|
|
// Update Schedule counts.
|
|
|
|
await updateScheduleInterestedCounts(users);
|
|
|
|
})
|