import NextAuth from "next-auth"; import Credentials from "next-auth/providers/credentials"; import bcrypt from "bcryptjs"; import { prisma } from "@/lib/prisma"; import type { Role } from "@prisma/client"; declare module "next-auth" { interface User { id: string; email: string; nombre: string; apellido: string; role: Role; empresaId: string; } interface Session { user: { id: string; email: string; nombre: string; apellido: string; role: Role; empresaId: string; }; } } declare module "@auth/core/jwt" { interface JWT { id: string; role: Role; empresaId: string; nombre: string; apellido: string; } } export const { handlers, auth, signIn, signOut } = NextAuth({ 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 prisma.user.findUnique({ where: { email: credentials.email as string }, include: { empresa: true }, }); if (!user || !user.activo) { return null; } const passwordMatch = await bcrypt.compare( credentials.password as string, user.password ); if (!passwordMatch) { return null; } return { id: user.id, email: user.email, nombre: user.nombre, apellido: user.apellido, role: user.role, empresaId: user.empresaId, }; }, }), ], callbacks: { async jwt({ token, user }) { if (user) { token.id = user.id; token.role = user.role; token.empresaId = user.empresaId; token.nombre = user.nombre; token.apellido = user.apellido; } return token; }, async session({ session, token }) { if (token) { session.user.id = token.id as string; session.user.role = token.role; session.user.empresaId = token.empresaId; session.user.nombre = token.nombre; session.user.apellido = token.apellido; } return session; }, }, pages: { signIn: "/login", error: "/login", }, session: { strategy: "jwt", maxAge: 24 * 60 * 60, // 24 hours }, });