52 lines
1.4 KiB
TypeScript
52 lines
1.4 KiB
TypeScript
import NextAuth from "next-auth"
|
|
import CredentialsProvider from "next-auth/providers/credentials"
|
|
import { prisma } from "@/lib/db"
|
|
import bcrypt from "bcryptjs"
|
|
import { z } from "zod"
|
|
|
|
const loginSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(1),
|
|
})
|
|
|
|
export default NextAuth({
|
|
providers: [
|
|
CredentialsProvider({
|
|
name: "credentials",
|
|
credentials: {
|
|
email: { label: "Email", type: "email" },
|
|
password: { label: "Password", type: "password" },
|
|
},
|
|
async authorize(credentials) {
|
|
try {
|
|
const { email, password } = loginSchema.parse(credentials)
|
|
const user = await prisma.user.findUnique({ where: { email } })
|
|
|
|
if (!user || !user.passwordHash) return null
|
|
|
|
const isValid = await bcrypt.compare(password, user.passwordHash)
|
|
if (!isValid) return null
|
|
|
|
return { id: user.id, email: user.email, name: user.name }
|
|
} catch {
|
|
return null
|
|
}
|
|
},
|
|
}),
|
|
],
|
|
session: { strategy: "jwt" },
|
|
pages: {
|
|
signIn: "/auth/login",
|
|
error: "/auth/error",
|
|
},
|
|
callbacks: {
|
|
async jwt({ token, user }) {
|
|
if (user) token.id = user.id
|
|
return token
|
|
},
|
|
async session({ session, token }) {
|
|
if (token.id) session.user.id = token.id
|
|
return session
|
|
},
|
|
},
|
|
}) |