2025-09-07 22:57:43 +00:00
|
|
|
// src/auth.ts
|
|
|
|
|
import NextAuth from "next-auth";
|
|
|
|
|
import Google from "next-auth/providers/google";
|
2025-09-08 18:49:58 +00:00
|
|
|
import { PrismaClient } from "@/app/generated/prisma";
|
|
|
|
|
import { randomBytes } from "crypto";
|
|
|
|
|
|
|
|
|
|
function generateRegisterCode(): string {
|
|
|
|
|
return randomBytes(16).toString("hex");
|
|
|
|
|
}
|
2025-09-07 22:57:43 +00:00
|
|
|
|
|
|
|
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
|
|
|
|
providers: [
|
|
|
|
|
Google({
|
|
|
|
|
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
|
|
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
|
|
|
}),
|
|
|
|
|
|
|
|
|
|
],
|
|
|
|
|
|
2025-09-08 18:30:34 +00:00
|
|
|
events: {
|
|
|
|
|
async signIn({ user, account, profile }) {
|
2025-09-08 18:49:58 +00:00
|
|
|
|
2025-09-08 18:30:34 +00:00
|
|
|
console.log("[NextAuth] signIn user:", {
|
|
|
|
|
id: (user as any)?.id,
|
|
|
|
|
name: user?.name,
|
|
|
|
|
email: user?.email,
|
|
|
|
|
image: (user as any)?.image,
|
|
|
|
|
provider: account?.provider,
|
|
|
|
|
});
|
2025-09-08 18:49:58 +00:00
|
|
|
|
|
|
|
|
// Upsert User (by email)
|
|
|
|
|
try {
|
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
|
const email = user?.email ?? "";
|
|
|
|
|
if (!email) {
|
|
|
|
|
console.warn("[NextAuth] Missing email, skip user upsert");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const existing = await prisma.user.findFirst({ where: { email } });
|
|
|
|
|
if (existing) {
|
|
|
|
|
const registerCodeData = existing.RegisgerCode
|
|
|
|
|
? {}
|
|
|
|
|
: { RegisgerCode: generateRegisterCode() };
|
|
|
|
|
await prisma.user.update({
|
|
|
|
|
where: { id: existing.id },
|
|
|
|
|
data: {
|
|
|
|
|
icon: (user as any)?.image ?? existing.icon,
|
|
|
|
|
...registerCodeData,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
await prisma.user.create({
|
|
|
|
|
data: {
|
|
|
|
|
email,
|
|
|
|
|
icon: (user as any)?.image ?? "",
|
|
|
|
|
RegisgerCode: generateRegisterCode(),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
await prisma.$disconnect();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error("[NextAuth] User upsert failed", e);
|
|
|
|
|
}
|
2025-09-08 18:30:34 +00:00
|
|
|
},
|
|
|
|
|
},
|
2025-09-07 22:57:43 +00:00
|
|
|
});
|