Add create account functionality

This commit is contained in:
Hornwitser 2025-03-07 23:53:57 +01:00
parent 598b9fd7d6
commit 8ef4636635
8 changed files with 145 additions and 12 deletions

View file

@ -0,0 +1,53 @@
import { readAccounts, writeAccounts, nextAccountId } from "~/server/database";
import { Account } from "~/shared/types/account";
export default defineEventHandler(async (event) => {
let session = await getAccountSession(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 accounts = await readAccounts();
let account: Account;
if (typeof name === "string") {
if (name === "") {
throw createError({
status: 400,
message: "Name cannot be blank",
});
}
if (accounts.some(account => account.name && account.name.toLowerCase() === name.toLowerCase())) {
throw createError({
status: 409,
message: "User already exists",
});
}
account = {
id: await nextAccountId(),
type: "regular",
name,
};
} else if (name === null) {
account = {
id: await nextAccountId(),
type: "anonymous",
};
} else {
throw createError({
status: 400,
message: "Invalid name",
});
}
accounts.push(account);
await writeAccounts(accounts);
await setAccountSession(event, account.id);
})