- Created registerUser server action with email/password validation - Implemented password hashing with bcrypt (10 rounds) - Added email uniqueness check to prevent duplicate registrations - Created session after successful registration using NextAuth - Added comprehensive validation for email format and password length (min 8 chars) - Added email and password validation utilities to lib/validation.ts - Removed PrismaAdapter from auth.ts (using JWT sessions only) - Added vitest testing framework and configuration - Created comprehensive unit tests for registration functionality - All tests passing (6/6) Requirements covered: 1.1, 1.2, 1.3, 1.4, 1.5
81 lines
1.9 KiB
TypeScript
81 lines
1.9 KiB
TypeScript
import NextAuth from "next-auth"
|
|
import Credentials from "next-auth/providers/credentials"
|
|
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({
|
|
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",
|
|
},
|
|
})
|