60 lines
1.6 KiB
TypeScript
60 lines
1.6 KiB
TypeScript
import { NextResponse } from "next/server"
|
|
import type { NextRequest } from "next/server"
|
|
import { jwtVerify } from "jose"
|
|
|
|
const RAW_SECRET = process.env.JWT_SECRET
|
|
if (!RAW_SECRET) {
|
|
throw new Error("JWT_SECRET environment variable is required")
|
|
}
|
|
const JWT_SECRET = new TextEncoder().encode(RAW_SECRET)
|
|
|
|
const publicRoutes = [
|
|
"/login",
|
|
"/api/auth/login",
|
|
"/api/auth/logout",
|
|
"/_next/static",
|
|
"/_next/image",
|
|
"/favicon.ico",
|
|
"/logo",
|
|
"/fonts",
|
|
]
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl
|
|
|
|
const isPublic = publicRoutes.some(
|
|
(route) => pathname === route || pathname.startsWith(route + "/") || pathname.startsWith(route)
|
|
)
|
|
|
|
if (isPublic) {
|
|
return NextResponse.next()
|
|
}
|
|
|
|
const sessionCookie = request.cookies.get("session")?.value
|
|
|
|
if (!sessionCookie) {
|
|
if (pathname.startsWith("/api/")) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
}
|
|
const loginUrl = new URL("/login", request.url)
|
|
loginUrl.searchParams.set("redirect", pathname)
|
|
return NextResponse.redirect(loginUrl)
|
|
}
|
|
|
|
try {
|
|
await jwtVerify(sessionCookie, JWT_SECRET)
|
|
return NextResponse.next()
|
|
} catch {
|
|
if (pathname.startsWith("/api/")) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
}
|
|
const loginUrl = new URL("/login", request.url)
|
|
loginUrl.searchParams.set("redirect", pathname)
|
|
return NextResponse.redirect(loginUrl)
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!_next/static|_next/image|favicon.ico|logo|fonts).*)"],
|
|
}
|