SPB Git forge
2commits 1branches 0releases
492.0 KBsize
maindefault branch
1 h agolast push
TypeScript 96.1% CSS 3.1% JavaScript 0.8%
1.4 KB · 43 lines typescript
Raw Blame History
1import { NextResponse } from "next/server";2import type { NextRequest } from "next/server";3import { SESSION_COOKIE, verifySession, checkBasicAuth } from "@/lib/auth";45// Protect the whole console. Browsers authenticate via the login cookie;6// API clients (e.g. the iOS app) may instead send HTTP Basic Auth.7export async function middleware(req: NextRequest) {8  const { pathname } = req.nextUrl;910  // Public paths: login page + the login API.11  if (pathname === "/login" || pathname === "/api/auth/login") {12    return NextResponse.next();13  }1415  const cookie = req.cookies.get(SESSION_COOKIE)?.value;16  const user = await verifySession(cookie);17  if (user) return NextResponse.next();1819  if (checkBasicAuth(req.headers.get("authorization"))) {20    return NextResponse.next();21  }2223  // Unauthenticated.24  if (pathname.startsWith("/api/")) {25    return NextResponse.json(26      { error: "Unauthorized" },27      { status: 401, headers: { "WWW-Authenticate": 'Basic realm="MacLustr"' } }28    );29  }3031  const url = req.nextUrl.clone();32  url.pathname = "/login";33  url.searchParams.set("from", pathname);34  return NextResponse.redirect(url);35}3637export const config = {38  // Run on everything except Next internals and static asset files (images/fonts).39  matcher: [40    "/((?!_next/static|_next/image|favicon.ico|robots.txt|.*\\.png$|.*\\.jpg$|.*\\.jpeg$|.*\\.svg$|.*\\.ico$|.*\\.webp$|.*\\.woff2?$).*)",41  ],42};43