This commit is contained in:
Tom Chien (IQ-AS)
2026-09-08 17:46:28 +08:00
commit e25c995560
55 changed files with 6928 additions and 0 deletions
+62
View File
@@ -0,0 +1,62 @@
import type { NextAuthConfig } from "next-auth";
import { NextResponse } from "next/server";
import type { Role } from "@/lib/authz";
// Admin-only page routes. Normal users are redirected away from these.
const ADMIN_PAGE_PREFIXES = [
"/cost-registration",
"/cost-item-creation",
"/year-creation",
];
// Edge-safe Auth.js config. This is imported by the middleware, which runs in
// the edge runtime, so it MUST NOT import Node APIs (node:fs) or the providers
// (Credentials/MicrosoftEntraID pull in Node crypto). The JSON allowlist is read
// only at sign-in in src/auth.ts (Node) and the resulting role is baked into the
// JWT; here we only read the role off the token.
export const authConfig = {
// Stateless JWT sessions — no DB adapter, keeps the middleware edge-compatible.
session: { strategy: "jwt" },
// Custom sign-in page offering both SSO and local username/password.
pages: { signIn: "/login" },
// Providers are added in the Node config (src/auth.ts). Empty here on purpose.
providers: [],
callbacks: {
// Copy the role from the token onto the session so server components /
// layout can read session.user.role.
session({ session, token }) {
if (session.user) {
session.user.role = token.role as Role | undefined;
}
return session;
},
// Runs in the middleware on every matched request. Enforces both
// authentication and role-based authorization server-side.
authorized({ auth, request }) {
const { pathname } = request.nextUrl;
// Always let the sign-in page through, even when unauthenticated.
if (pathname === "/login") return true;
// Not signed in -> Auth.js redirects to the sign-in page.
if (!auth?.user) return false;
const role = auth.user.role;
// Admin is required for admin page routes and for any write API call
// (all mutations are non-GET requests to /api/*).
const needsAdmin =
ADMIN_PAGE_PREFIXES.some((prefix) => pathname.startsWith(prefix)) ||
(pathname.startsWith("/api/") && request.method !== "GET");
if (needsAdmin && role !== "admin") {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
return NextResponse.redirect(new URL("/", request.url));
}
return true;
},
},
} satisfies NextAuthConfig;