Replace all async reads and writes to the JSON database with the sync reads and writes to prevent a data corruption race condition where two requests are processed at the same time and write to the same file, or one reads while the other writes causing read of partially written data.
38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import { readAuthenticationMethods, readUsers } from "~/server/database";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const runtimeConfig = useRuntimeConfig(event);
|
|
if (!runtimeConfig.public.authDemoEnabled) {
|
|
throw createError({
|
|
statusCode: 403,
|
|
statusMessage: "Forbidden",
|
|
message: "Demo authentication is disabled",
|
|
});
|
|
}
|
|
|
|
const { name: slug } = await readBody(event);
|
|
|
|
if (typeof slug !== "string" || !slug) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: "Bad Request",
|
|
message: "Missing name",
|
|
});
|
|
}
|
|
|
|
const authMethods = readAuthenticationMethods();
|
|
const method = authMethods.find(method => method.provider === "demo" && method.slug === slug);
|
|
let session;
|
|
if (method) {
|
|
const users = readUsers();
|
|
const account = users.find(user => !user.deleted && user.id === method.userId);
|
|
session = await setServerSession(event, account);
|
|
} else {
|
|
session = await setServerSession(event, undefined, "demo", slug, slug);
|
|
}
|
|
return await serverSessionToApi(event, session);
|
|
})
|