import NextAuth from "next-auth"; import { PrismaAdapter } from "@auth/prisma-adapter"; import { prisma } from "@/lib/prisma"; import authConfig from "./auth.config"; export const { handlers, signIn, signOut, auth } = NextAuth({ adapter: PrismaAdapter(prisma), session: { strategy: "jwt" }, ...authConfig, callbacks: { async jwt({ token, account, user }) { // 1. Handle OAuth tokens (from first sign-in) if (account) { token.accessToken = account.access_token; token.refreshToken = account.refresh_token; token.expiresAt = account.expires_at; } // 2. Attach User ID and Role to the token // When 'user' exists, it's the first time we've fetched this user from the DB during login if (user) { token.sub = user.id; // @ts-ignore - 'role' exists on our custom User model token.role = user.role; } return token; }, async session({ session, token }) { // 3. Pass values from the JWT Token into the Client-facing Session if (session?.user && token.sub) { session.user.id = token.sub; // @ts-ignore - Attaching the role so the Navbar and Settings page can see it session.user.role = token.role; } return session; }, }, events: { async linkAccount({ account, user }) { console.log("🔗 Account linked successfully for user:", user.id); if (!account.refresh_token) { console.warn("⚠️ WARNING: No refresh_token received in linkAccount event!"); } } } });