import NextAuth, { type NextAuthOptions } from "next-auth"; import GoogleProvider from "next-auth/providers/google"; const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://127.0.0.1:8000"; const googleClientId = process.env.GOOGLE_CLIENT_ID ?? ""; const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET ?? ""; export const authOptions: NextAuthOptions = { providers: googleClientId && googleClientSecret ? [ GoogleProvider({ clientId: googleClientId, clientSecret: googleClientSecret, }), ] : [], session: { strategy: "jwt" as const }, callbacks: { async signIn({ account }) { if (account?.provider === "google" && account.id_token) { try { const response = await fetch(`${apiBase}/auth/google`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id_token: account.id_token }), }); if (!response.ok) { console.error("Google verification failed", await response.text()); return false; } const payload = await response.json(); const enrichedAccount = account as Record; enrichedAccount.userId = payload.user_id; enrichedAccount.userEmail = payload.email; enrichedAccount.userName = payload.display_name; } catch (error) { console.error("Google auth request failed", error); return false; } } return true; }, async jwt({ token, account }) { if (account) { const enrichedAccount = account as Record; token.userId = (enrichedAccount.userId as string | undefined) ?? token.userId; token.email = (enrichedAccount.userEmail as string | undefined) ?? token.email; token.name = (enrichedAccount.userName as string | undefined) ?? token.name; } return token; }, async session({ session, token }) { if (session.user) { session.user.id = token.userId; } return session; }, }, pages: { signIn: "/", }, secret: process.env.NEXTAUTH_SECRET, }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };