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; +}