feat: set up authentication infrastructure with NextAuth.js v5

- Install next-auth@beta, bcryptjs, zod, and @auth/prisma-adapter
- Create auth.ts with credentials provider and JWT session strategy
- Create auth.config.ts for edge-compatible middleware configuration
- Add NextAuth type extensions for session and JWT
- Create API route handler for authentication
- Configure environment variables for NextAuth
- Add AUTH_SETUP.md documentation

Task: 1. Set up authentication infrastructure
Requirements: 1.1, 2.1
This commit is contained in:
2025-12-01 23:56:45 +00:00
parent b3c7f92877
commit 2c3b66b085
12 changed files with 1602 additions and 3 deletions

82
auth.ts Normal file
View File

@@ -0,0 +1,82 @@
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { prisma } from "@/lib/db"
import bcrypt from "bcryptjs"
import { z } from "zod"
// Validation schemas
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
})
export const { handlers, signIn, signOut, auth } = NextAuth({
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt",
},
providers: [
Credentials({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
try {
// Validate credentials format
const { email, password } = loginSchema.parse(credentials)
// Query user from database
const user = await prisma.user.findUnique({
where: { email },
})
// Check if user exists
if (!user || !user.passwordHash) {
return null
}
// Verify password with bcrypt
const isPasswordValid = await bcrypt.compare(password, user.passwordHash)
if (!isPasswordValid) {
return null
}
// Return user object (without password hash)
return {
id: user.id,
email: user.email,
name: user.name,
}
} catch (error) {
console.error("Authorization error:", error)
return null
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
// Add user ID to token on sign in
if (user) {
token.id = user.id
}
return token
},
async session({ session, token }) {
// Add user ID to session from token
if (session.user) {
session.user.id = token.id as string
}
return session
},
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
error: "/auth/error",
},
})