diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts index 786f664..c42d23e 100644 --- a/src/app/api/auth/[...nextauth]/route.ts +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -11,7 +11,7 @@ import { accounts, verificationTokens, } from "@/app/db/schema/users"; -import { eq } from "drizzle-orm"; +import { eq, and } from "drizzle-orm"; // ------------------------------------------------------------------ // Environment variables @@ -102,7 +102,7 @@ export const AuthOptions: NextAuthOptions = { /** * Sign in callback — ensures user exists and links OAuth provider if needed */ - async signIn({ user, account }) { + async signIn({ user, account, profile }) { try { if (!user?.email) return false; const normalisedEmail = user.email.toLowerCase(); @@ -113,11 +113,50 @@ export const AuthOptions: NextAuthOptions = { .from(users) .where(eq(users.email, normalisedEmail)); + // New user - next auth will handle if (!dbUser) { console.log("New user sign up for email:", normalisedEmail); return true; } + // Auto-link provider if same verified email but account not linked yet + if (account?.provider && account.type === "oauth") { + const existingLink = await db + .select() + .from(accounts) + .where( + and( + eq(accounts.userId, dbUser.id), + eq(accounts.provider, account.provider) + ) + ); + + const emailVerified = + (profile as any)?.email_verified ?? account.provider === "google"; + + if (existingLink.length === 0 && emailVerified) { + // This handles the case where we had not set up accounts but + // signed up users with oauth + console.log( + `Linking ${account.provider} account for user ${normalisedEmail}` + ); + + await db + .insert(accounts) + .values({ + userId: dbUser.id, + type: account.type, + provider: account.provider, + providerAccountId: account.providerAccountId, + access_token: account.access_token, + id_token: account.id_token, + refresh_token: account.refresh_token, + expires_at: account.expires_at, + }) + .onConflictDoNothing(); + } + } + // Link OAuth ID if missing (helps for older accounts) if (account && !dbUser.oauthId) { console.log("Linking OAuth ID for user:", normalisedEmail);