echos-ocr/src/middleware.ts

84 lines
1.9 KiB
TypeScript
Raw Normal View History

import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
const publicPaths = [
"/login",
"/signup",
"/invite",
"/setup",
"/api/auth",
"/api/health",
"/api/setup",
"/api/onboarding",
"/api/invitations/verify",
"/api/jobs/process",
"/api/email-watch/poll",
"/api/ftp-watch/poll",
];
const onboardingExemptPaths = [
"/onboarding",
"/api/onboarding",
"/api/auth",
];
function isPublic(pathname: string) {
return publicPaths.some(
(p) => pathname === p || pathname.startsWith(p + "/")
);
}
function isOnboardingExempt(pathname: string) {
return onboardingExemptPaths.some(
(p) => pathname === p || pathname.startsWith(p + "/")
);
}
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/favicon") ||
pathname.includes(".")
) {
return NextResponse.next();
}
if (isPublic(pathname)) {
return NextResponse.next();
}
const secureCookie =
req.headers.get("x-forwarded-proto") === "https" ||
req.nextUrl.protocol === "https:";
const token = await getToken({
req,
secret: process.env.AUTH_SECRET,
secureCookie,
});
if (!token) {
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
const hasOrg = !!token.orgId;
const onboardingDone = token.onboardingComplete === true;
if (!hasOrg && !isOnboardingExempt(pathname)) {
return NextResponse.redirect(new URL("/onboarding", req.url));
}
if (hasOrg && !onboardingDone && !isOnboardingExempt(pathname)) {
return NextResponse.redirect(new URL("/onboarding", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};