2026-10-06 02:02:08 +00:00
import { NextRequest , NextResponse } from "next/server" ;
2026-10-21 04:39:15 +00:00
import { clockAuthDestination } from "@/lib/clock-pwa" ;
2026-10-06 02:02:08 +00:00
import { sessionFromToken } from "@/lib/auth-service" ;
import { SESSION_COOKIE , authDestination } from "@/lib/auth-policy" ;
export async function proxy ( request : NextRequest ) {
const path = request . nextUrl . pathname ;
2026-10-21 04:39:15 +00:00
if ( path === "/api/health" || path === "/api/auth/logout" || path === "/login" || path === "/clock/login" || path === "/clock.webmanifest" ) return NextResponse . next ( ) ;
2026-10-06 02:02:08 +00:00
let session ;
try {
session = await sessionFromToken ( request . cookies . get ( SESSION_COOKIE ) ? . value || "" ) ;
} catch {
return path . startsWith ( "/api/" )
? NextResponse . json ( { error : "Account service is temporarily unavailable." } , { status : 503 } )
: new NextResponse ( "Account service is temporarily unavailable. Please reload to try again." , { status : 503 , headers : { "Content-Type" : "text/plain; charset=utf-8" , "Cache-Control" : "no-store" } } ) ;
}
2026-10-21 04:39:15 +00:00
const clockPath = path === "/clock" || path . startsWith ( "/clock/" ) ;
const destination = clockPath ? clockAuthDestination ( session ) : authDestination ( session ) ;
2026-10-06 02:02:08 +00:00
// Logout is a server action and remains available during first-login onboarding.
2026-10-21 04:39:15 +00:00
if ( ( path === "/change-password" || path === "/clock/change-password" ) && session ) return NextResponse . next ( ) ;
if ( destination !== ( clockPath ? "/clock" : "/" ) ) {
2026-10-06 02:02:08 +00:00
if ( path . startsWith ( "/api/" ) ) return NextResponse . json ( { error : session ? "Change your starter password first." : "Please sign in." } , { status : session ? 403 : 401 } ) ;
return NextResponse . redirect ( new URL ( destination , request . url ) ) ;
}
const response = NextResponse . next ( ) ;
response . headers . set ( "Cache-Control" , "private, no-store" ) ;
return response ;
}
export const config = {
matcher : [ "/((?!_next/static|_next/image|brand/|icons/|favicon\\.ico|manifest\\.json|sw\\.js|workbox-[^/]+\\.js|swe-worker-[^/]+\\.js|worker-[^/]+\\.js).*)" ] ,
} ;