login logic fix

This commit is contained in:
2025-09-08 18:49:58 +00:00
parent a93493fb62
commit 0cce0322a1
5 changed files with 133 additions and 3 deletions

42
auth.ts
View File

@@ -1,6 +1,12 @@
// src/auth.ts
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import { PrismaClient } from "@/app/generated/prisma";
import { randomBytes } from "crypto";
function generateRegisterCode(): string {
return randomBytes(16).toString("hex");
}
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
@@ -13,6 +19,7 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
events: {
async signIn({ user, account, profile }) {
console.log("[NextAuth] signIn user:", {
id: (user as any)?.id,
name: user?.name,
@@ -20,6 +27,41 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
image: (user as any)?.image,
provider: account?.provider,
});
// 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);
}
},
},
});