Files
ef_front/auth.ts

63 lines
1.8 KiB
TypeScript
Raw Normal View History

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";
2025-09-09 00:15:08 +00:00
async function generateRegisterCode(): Promise<string> {
// Library-free random (Edge 호환). 16바이트 hex
let out = "";
for (let i = 0; i < 16; i++) {
const byte = Math.floor(Math.random() * 256);
out += byte.toString(16).padStart(2, "0");
}
return out;
2025-09-08 18:49:58 +00:00
}
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-09 00:15:08 +00:00
// callbacks 제거: 세션에 registerCode를 포함하지 않음
2025-09-07 22:57:43 +00:00
2025-09-08 18:30:34 +00:00
events: {
async signIn({ user, account, profile }) {
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
? {}
2025-09-09 00:15:08 +00:00
: { RegisgerCode: await generateRegisterCode() };
2025-09-08 18:49:58 +00:00
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 ?? "",
2025-09-09 00:15:08 +00:00
RegisgerCode: await generateRegisterCode(),
2025-09-08 18:49:58 +00:00
},
});
}
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
});