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:
@@ -0,0 +1,6 @@
|
||||
import NextAuth from "next-auth";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -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;
|
||||
},
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user