26 lines
965 B
TypeScript
26 lines
965 B
TypeScript
// Gates every /api/** route. Static SPA assets stay public.
|
|
export default defineEventHandler(async (event) => {
|
|
const path = getRequestURL(event).pathname;
|
|
if (!path.startsWith("/api/")) return;
|
|
|
|
// Dev-only bypass for local smoke tests. `import.meta.dev` is false in production
|
|
// builds, so this branch is dead-code-eliminated and can never run when deployed.
|
|
if (import.meta.dev && process.env.AUTH_DEV_BYPASS === "1") {
|
|
event.context.user = { sub: "dev" };
|
|
return;
|
|
}
|
|
|
|
// CORS preflight is answered (and short-circuited) by 0.cors.ts before this runs.
|
|
const header = getHeader(event, "authorization") || "";
|
|
const token = header.startsWith("Bearer ") ? header.slice(7).trim() : "";
|
|
if (!token) {
|
|
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
|
|
}
|
|
|
|
try {
|
|
event.context.user = await getVerifier()(token);
|
|
} catch {
|
|
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
|
|
}
|
|
});
|