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

View File

@@ -6,7 +6,6 @@ import { randomBytes } from 'crypto';
export async function GET(request: Request) {
const session = await auth();
if (!session) {
console.log(session)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {

View File

@@ -5,7 +5,6 @@ import NavBar from '@/app/components/NavBar';
export default function Layout({ children , session}: { children: React.ReactNode , session: any }) {
const [isOpen, setIsOpen] = useState(false);
console.log(session);
return (
<div className="bg-[#F5F5F5] h-full flex flex-row " onClick={() => setIsOpen(false)}>
<NavBar isOpen={isOpen} setIsOpen={setIsOpen} user={session?.user} />

View File

@@ -53,7 +53,6 @@ export default function Page() {
const response = await fetch('/api/notice');
const data = await response.json();
setNoticeList(data);
console.log(data);
}
useEffect(() => {

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);
}
},
},
});

View File

@@ -0,0 +1,91 @@
/*
Warnings:
- You are about to drop the `content` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `handle` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `registerChannel` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `user` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE `content` DROP FOREIGN KEY `content_handleId_fkey`;
-- DropForeignKey
ALTER TABLE `handle` DROP FOREIGN KEY `handle_userId_fkey`;
-- DropTable
DROP TABLE `content`;
-- DropTable
DROP TABLE `handle`;
-- DropTable
DROP TABLE `registerChannel`;
-- DropTable
DROP TABLE `user`;
-- CreateTable
CREATE TABLE `User` (
`id` VARCHAR(191) NOT NULL,
`email` VARCHAR(191) NOT NULL,
`icon` VARCHAR(191) NOT NULL DEFAULT '',
`isApproved` BOOLEAN NOT NULL DEFAULT false,
`createtime` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`RegisgerCode` VARCHAR(191) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `RegisterChannel` (
`id` VARCHAR(191) NOT NULL,
`handle` VARCHAR(191) NOT NULL,
`userId` VARCHAR(191) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Handle` (
`id` VARCHAR(191) NOT NULL,
`handle` VARCHAR(191) NOT NULL,
`constPerView` DOUBLE NOT NULL DEFAULT 1,
UNIQUE INDEX `Handle_handle_key`(`handle`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `Content` (
`id` VARCHAR(191) NOT NULL,
`subject` VARCHAR(191) NOT NULL,
`pubDate` DATETIME(3) NOT NULL,
`handleId` VARCHAR(191) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `_HandleToUser` (
`A` VARCHAR(191) NOT NULL,
`B` VARCHAR(191) NOT NULL,
UNIQUE INDEX `_HandleToUser_AB_unique`(`A`, `B`),
INDEX `_HandleToUser_B_index`(`B`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `RegisterChannel` ADD CONSTRAINT `RegisterChannel_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `Content` ADD CONSTRAINT `Content_handleId_fkey` FOREIGN KEY (`handleId`) REFERENCES `Handle`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `contentDayView` ADD CONSTRAINT `contentDayView_contentId_fkey` FOREIGN KEY (`contentId`) REFERENCES `Content`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_HandleToUser` ADD CONSTRAINT `_HandleToUser_A_fkey` FOREIGN KEY (`A`) REFERENCES `Handle`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `_HandleToUser` ADD CONSTRAINT `_HandleToUser_B_fkey` FOREIGN KEY (`B`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;