feat(02-01): install next-auth@4, configure CredentialsProvider auth

- Add next-auth@4 dependency (stable v4, not beta v5)
- Create src/lib/auth.ts with CredentialsProvider validating ADMIN_EMAIL/ADMIN_PASSWORD env vars
- Create src/app/api/auth/[...nextauth]/route.ts catch-all handler (GET + POST)
- JWT session strategy — stateless, no DB users table
- Custom sign-in page set to /admin/login
- Add NEXTAUTH_URL, NEXTAUTH_SECRET, ADMIN_EMAIL, ADMIN_PASSWORD to .env.local
This commit is contained in:
Simone Cavalli
2026-05-15 10:40:30 +02:00
parent 56dd18b0c2
commit 5d363a633d
4 changed files with 226 additions and 0 deletions
+55
View File
@@ -0,0 +1,55 @@
import type { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const adminEmail = process.env.ADMIN_EMAIL;
const adminPassword = process.env.ADMIN_PASSWORD;
if (!adminEmail || !adminPassword) {
throw new Error("ADMIN_EMAIL and ADMIN_PASSWORD env vars must be set");
}
if (
credentials.email === adminEmail &&
credentials.password === adminPassword
) {
// Return minimal session user — no DB lookup needed
return { id: "admin", email: adminEmail, name: "Admin" };
}
return null; // null = unauthorized (NextAuth returns 401)
},
}),
],
session: {
strategy: "jwt", // stateless JWT — no DB session table (per D-03)
maxAge: 30 * 24 * 60 * 60, // 30 days
},
pages: {
signIn: "/admin/login", // custom login page (per D-07)
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
async session({ session, token }) {
if (session.user) {
(session.user as { id?: string }).id = token.id as string;
}
return session;
},
},
};