You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
939 B
37 lines
939 B
import type { H3Event } from "h3";
|
|
import { SESSION_COOKIE_NAME, UNAUTHORIZED_MESSAGE } from "#server/constants/auth";
|
|
import { getCurrentUser, type MinimalUser } from ".";
|
|
|
|
export function createAuthContext(event: H3Event) {
|
|
let currentUserPromise: Promise<MinimalUser | null> | 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,
|
|
};
|
|
}
|
|
|