owltide/server/api/auth/ap/demo-login.post.ts
Hornwitser 0d0e38e4b6 Refactor demo login as an authentication method
Use the authentication method system for the demo login and the
generated accounts.  This makes it possible to toggle it off on
production systems as these shouldn't have it enabled at all.
2025-07-09 18:01:26 +02:00

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 = await readAuthenticationMethods();
const method = authMethods.find(method => method.provider === "demo" && method.slug === slug);
let session;
if (method) {
const users = await 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);
})