2026-01-08 05:41:31 +00:00
|
|
|
import NextAuth from "next-auth";
|
|
|
|
|
import { PrismaAdapter } from "@auth/prisma-adapter";
|
|
|
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
|
import authConfig from "./auth.config";
|
|
|
|
|
|
2026-01-06 02:40:21 +00:00
|
|
|
export const { handlers, signIn, signOut, auth } = NextAuth({
|
2026-01-08 05:41:31 +00:00
|
|
|
adapter: PrismaAdapter(prisma),
|
|
|
|
|
session: { strategy: "jwt" },
|
|
|
|
|
...authConfig,
|
|
|
|
|
callbacks: {
|
|
|
|
|
async jwt({ token, account, user }) {
|
2026-01-11 13:41:54 +00:00
|
|
|
// 1. Handle OAuth tokens (from first sign-in)
|
2026-01-08 05:41:31 +00:00
|
|
|
if (account) {
|
|
|
|
|
token.accessToken = account.access_token;
|
|
|
|
|
token.refreshToken = account.refresh_token;
|
|
|
|
|
token.expiresAt = account.expires_at;
|
|
|
|
|
}
|
2026-01-11 13:41:54 +00:00
|
|
|
|
|
|
|
|
// 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
|
2026-01-08 05:41:31 +00:00
|
|
|
if (user) {
|
|
|
|
|
token.sub = user.id;
|
2026-01-11 13:41:54 +00:00
|
|
|
// @ts-ignore - 'role' exists on our custom User model
|
|
|
|
|
token.role = user.role;
|
2026-01-08 05:41:31 +00:00
|
|
|
}
|
2026-01-11 13:41:54 +00:00
|
|
|
|
2026-01-08 05:41:31 +00:00
|
|
|
return token;
|
|
|
|
|
},
|
2026-01-11 13:41:54 +00:00
|
|
|
|
2026-01-08 05:41:31 +00:00
|
|
|
async session({ session, token }) {
|
2026-01-11 13:41:54 +00:00
|
|
|
// 3. Pass values from the JWT Token into the Client-facing Session
|
2026-01-08 05:41:31 +00:00
|
|
|
if (session?.user && token.sub) {
|
|
|
|
|
session.user.id = token.sub;
|
2026-01-11 13:41:54 +00:00
|
|
|
// @ts-ignore - Attaching the role so the Navbar and Settings page can see it
|
|
|
|
|
session.user.role = token.role;
|
2026-01-08 05:41:31 +00:00
|
|
|
}
|
|
|
|
|
return session;
|
|
|
|
|
},
|
|
|
|
|
},
|
2026-01-11 13:41:54 +00:00
|
|
|
|
2026-01-08 05:41:31 +00:00
|
|
|
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!");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|