import { NextAuthOptions, getServerSession } from "next-auth"; import CredentialsProvider from "next-auth/providers/credentials"; import { compare } from "bcryptjs"; import { db } from "@/lib/db"; import { UserRole } from "@prisma/client"; declare module "next-auth" { interface Session { user: { id: string; email: string; name: string; role: UserRole; mustChangePassword: boolean; }; } interface User { id: string; role: UserRole; mustChangePassword: boolean; } } declare module "next-auth/jwt" { interface JWT { id: string; role: UserRole; mustChangePassword: boolean; } } // Fail loudly in production if the JWT secret is missing or left at the // placeholder — otherwise sessions are forgeable. Skipped during `next build` // (no runtime env) and in development. const NEXTAUTH_SECRET = process.env.NEXTAUTH_SECRET; if ( process.env.NODE_ENV === "production" && process.env.NEXT_PHASE !== "phase-production-build" && (!NEXTAUTH_SECRET || NEXTAUTH_SECRET.length < 16 || NEXTAUTH_SECRET.includes("change-me")) ) { throw new Error( "NEXTAUTH_SECRET is missing or insecure — generate one with `openssl rand -base64 32` and set it in the environment." ); } export const authOptions: NextAuthOptions = { secret: NEXTAUTH_SECRET, session: { strategy: "jwt" }, pages: { signIn: "/login", error: "/login" }, providers: [ CredentialsProvider({ name: "credentials", credentials: { email: { label: "Username or email", type: "text" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { if (!credentials?.email || !credentials?.password) return null; const id = credentials.email.trim(); const user = await db.user.findFirst({ where: { active: true, OR: [ { email: id.toLowerCase() }, { username: { equals: id, mode: "insensitive" } }, ], }, select: { id: true, name: true, email: true, passwordHash: true, role: true, mustChangePassword: true, }, }); if (!user) return null; const ok = await compare(credentials.password, user.passwordHash); if (!ok) return null; return { id: user.id, email: user.email, name: user.name, role: user.role, mustChangePassword: user.mustChangePassword, }; }, }), ], callbacks: { async jwt({ token, user, trigger }) { if (user) { token.id = user.id; token.role = user.role; token.mustChangePassword = user.mustChangePassword; } if (trigger === "update") { const fresh = await db.user.findUnique({ where: { id: token.id }, select: { mustChangePassword: true }, }); if (fresh) token.mustChangePassword = fresh.mustChangePassword; } return token; }, async session({ session, token }) { session.user.id = token.id; session.user.role = token.role; session.user.mustChangePassword = token.mustChangePassword; return session; }, }, }; export const getSession = () => getServerSession(authOptions); export async function requireAuth() { const session = await getSession(); if (!session) throw new Error("Unauthorized"); return session; } export function isAdmin(role: UserRole): boolean { return role === "ADMIN"; }