import type { H3Event } from "h3"; import { SESSION_COOKIE_NAME, UNAUTHORIZED_MESSAGE } from "#server/constants/auth"; import { getCurrentUser } from "."; type MinimalUser = { id: number; username: string; }; export function createAuthContext(event: H3Event) { let currentUserPromise: Promise | undefined; const getCurrent = async () => { if (!currentUserPromise) { currentUserPromise = (async () => { const sessionId = getCookie(event, SESSION_COOKIE_NAME); if (!sessionId) { return null; } return getCurrentUser(sessionId); })(); } return currentUserPromise; }; const requireUser = async () => { const user = await getCurrent(); if (!user) { throw createError({ statusCode: 401, statusMessage: UNAUTHORIZED_MESSAGE, data: { code: "UNAUTHORIZED" }, }); } return user; }; return { getCurrent, requireUser, }; }