owltide/server/api/auth/account.post.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

64 lines
1.5 KiB
TypeScript

/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers, writeUsers, nextUserId, type ServerUser } from "~/server/database";
import { broadcastEvent } from "~/server/streams";
export default defineEventHandler(async (event) => {
let session = await getServerSession(event);
if (session) {
throw createError({
status: 409,
message: "Cannot create account while having an active session."
});
}
const formData = await readFormData(event);
const name = formData.get("name");
const users = await readUsers();
let user: ServerUser;
if (typeof name === "string") {
if (name === "") {
throw createError({
status: 400,
message: "Name cannot be blank",
});
}
if (users.some(user => user.name && user.name.toLowerCase() === name.toLowerCase())) {
throw createError({
status: 409,
message: "User already exists",
});
}
const firstUser = users.every(user => user.type === "anonymous");
user = {
id: await nextUserId(),
updatedAt: new Date().toISOString(),
type: firstUser ? "admin" : "regular",
name,
};
} else if (name === null) {
user = {
id: await nextUserId(),
updatedAt: new Date().toISOString(),
type: "anonymous",
};
} else {
throw createError({
status: 400,
message: "Invalid name",
});
}
users.push(user);
await writeUsers(users);
await broadcastEvent({
type: "user-update",
data: user,
});
await setServerSession(event, user);
})