1import { NextRequest, NextResponse } from "next/server";
2
3
13const SESSION_COOKIE = "factory_refresh";
14
15const PUBLIC_PREFIXES = ["/login", "/register", "/reset-password", "/share/", "/f/", "/health"];
16
17
18const PUBLIC_PATH_PREFIXES = ["/_next", "/favicon.ico", "/robots.txt", "/sitemap.xml"];
19
20function isPublicPath(pathname: string): boolean {
21 if (PUBLIC_PATH_PREFIXES.some((p) => pathname.startsWith(p))) return true;
22 return PUBLIC_PREFIXES.some((p) => (p.endsWith("/") ? pathname.startsWith(p) : pathname === p));
23}
24
25export function middleware(request: NextRequest): NextResponse {
26 const { pathname } = request.nextUrl;
27 const hasSession = request.cookies.has(SESSION_COOKIE);
28
29
30 if (hasSession && (pathname === "/login" || pathname === "/register" || pathname === "/reset-password")) {
31 const redirect = request.nextUrl.clone();
32 redirect.pathname = "/w/default";
33 redirect.search = "";
34 return NextResponse.redirect(redirect);
35 }
36
37
38 if (!hasSession && !isPublicPath(pathname)) {
39 const login = request.nextUrl.clone();
40 login.pathname = "/login";
41 login.search = "";
42 login.searchParams.set("next", pathname + request.nextUrl.search);
43 return NextResponse.redirect(login);
44 }
45
46 return NextResponse.next();
47}
48
49export const config = {
50 matcher: [
51
52 "/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml).*)"
53 ]
54};
55