import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { SESSION_COOKIE, verifySession, checkBasicAuth } from "@/lib/auth"; // Protect the whole console. Browsers authenticate via the login cookie; // API clients (e.g. the iOS app) may instead send HTTP Basic Auth. export async function middleware(req: NextRequest) { const { pathname } = req.nextUrl; // Public paths: login page + the login API. if (pathname === "/login" || pathname === "/api/auth/login") { return NextResponse.next(); } const cookie = req.cookies.get(SESSION_COOKIE)?.value; const user = await verifySession(cookie); if (user) return NextResponse.next(); if (checkBasicAuth(req.headers.get("authorization"))) { return NextResponse.next(); } // Unauthenticated. if (pathname.startsWith("/api/")) { return NextResponse.json( { error: "Unauthorized" }, { status: 401, headers: { "WWW-Authenticate": 'Basic realm="MacLustr"' } } ); } const url = req.nextUrl.clone(); url.pathname = "/login"; url.searchParams.set("from", pathname); return NextResponse.redirect(url); } export const config = { // Run on everything except Next internals and static asset files (images/fonts). matcher: [ "/((?!_next/static|_next/image|favicon.ico|robots.txt|.*\\.png$|.*\\.jpg$|.*\\.jpeg$|.*\\.svg$|.*\\.ico$|.*\\.webp$|.*\\.woff2?$).*)", ], };