import NextAuth from "next-auth"; import { PrismaAdapter } from "@auth/prisma-adapter"; import Credentials from "next-auth/providers/credentials"; import { db } from "@/lib/db"; import bcrypt from "bcryptjs"; import { Role } from "@prisma/client"; export const { handlers, auth, signIn, signOut } = NextAuth({ adapter: PrismaAdapter(db) as any, session: { strategy: "jwt" }, pages: { signIn: "/login", }, callbacks: { async jwt({ token, user }) { if (user) { token.id = user.id; token.role = (user as { role: Role }).role; token.mustChangePassword = (user as { mustChangePassword?: boolean }).mustChangePassword ?? false; } return token; }, async session({ session, token }) { if (token && session.user) { session.user.id = token.id as string; session.user.role = token.role as Role; session.user.mustChangePassword = token.mustChangePassword as boolean; } return session; }, }, providers: [ Credentials({ name: "credentials", credentials: { email: { label: "Email", type: "email" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { if (!credentials?.email || !credentials?.password) return null; const user = await db.user.findUnique({ where: { email: credentials.email as string }, }); if (!user || !user.passwordHash || !user.isActive) return null; const isValid = await bcrypt.compare( credentials.password as string, user.passwordHash ); if (!isValid) return null; return { id: user.id, email: user.email, name: user.name, image: user.image, role: user.role, mustChangePassword: user.mustChangePassword, }; }, }), ], });