owltide/server/api/admin/user.patch.ts
Hornwitser e52972853d License under AGPL version 3 or later
I firmly believe in free software.

The application I'm making here have capabilities that I've not seen in
any system.  It presents itself as an opportunity to collaborate on a
tool that serves the people rather than corporations.  Whose incentives
are to help people rather, not make the most money.  And whose terms
ensure that these freedoms and incentives cannot be taken back or
subverted.

I license this software under the AGPL.
2025-06-30 18:58:24 +02:00

61 lines
1.5 KiB
TypeScript

/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers, writeUsers } from "~/server/database";
import { apiUserPatchSchema } from "~/shared/types/api";
import { z } from "zod/v4-mini";
import { broadcastEvent } from "~/server/streams";
export default defineEventHandler(async (event) => {
await requireServerSessionWithAdmin(event);
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);
})