From ada2f249ee92d6315110c0d4b9b53a12c8f4273a Mon Sep 17 00:00:00 2001 From: goddonebianu Date: Mon, 16 Mar 2026 09:24:57 +0800 Subject: [PATCH] refactor: add shared utilities and replace console.log with logger - Add shared action-utils.ts with getCurrentUserId and requireAuth helpers - Add shared constants for anki defaults (FIELD_SEPARATOR, DEFAULT_NEW_PER_DAY, DEFAULT_REV_PER_DAY) - Add shared time constants (SECONDS_PER_DAY, MS_PER_DAY, etc.) - Replace console.error with logger in auth.ts --- src/auth.ts | 8 ++++++-- src/modules/shared/action-utils.ts | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 src/modules/shared/action-utils.ts diff --git a/src/auth.ts b/src/auth.ts index c7d0efc..055d776 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -4,6 +4,10 @@ import { nextCookies } from "better-auth/next-js"; import { username } from "better-auth/plugins"; import { createAuthMiddleware, APIError } from "better-auth/api"; import { prisma } from "./lib/db"; +import { createLogger } from "./lib/logger"; + +const log = createLogger("auth"); + import { sendEmail, generateVerificationEmailHtml, @@ -24,7 +28,7 @@ export const auth = betterAuth({ html: generateResetPasswordEmailHtml(url, user.name || "用户"), }); if (!result.success) { - console.error("[email] Failed to send reset password email:", result.error); + log.error("Failed to send reset password email", { error: result.error }); } }, }, @@ -38,7 +42,7 @@ export const auth = betterAuth({ html: generateVerificationEmailHtml(url, user.name || "用户"), }); if (!result.success) { - console.error("[email] Failed to send verification email:", result.error); + log.error("Failed to send verification email", { error: result.error }); } }, }, diff --git a/src/modules/shared/action-utils.ts b/src/modules/shared/action-utils.ts new file mode 100644 index 0000000..c968ab8 --- /dev/null +++ b/src/modules/shared/action-utils.ts @@ -0,0 +1,25 @@ +"use server-headers"; + +import { auth } from "@/auth"; +import { headers } from "next/headers"; +import { createLogger } from "@/lib/logger"; + +const log = createLogger("shared-action-utils"); + +export async function getCurrentUserId(): Promise { + const session = await auth.api.getSession({ headers: await headers() }); + if (!session?.user?.id) { + log.warn("Unauthenticated access attempt"); + return null; + } + return session.user.id; +} + +export async function requireAuth(): Promise { + const userId = await getCurrentUserId(); + if (!userId) { + log.warn("Authentication required but rejected"); + throw new Error("Unauthorized"); + } + return userId; +}