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
This commit is contained in:
@@ -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 });
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
25
src/modules/shared/action-utils.ts
Normal file
25
src/modules/shared/action-utils.ts
Normal file
@@ -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<string | null> {
|
||||
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<string> {
|
||||
const userId = await getCurrentUserId();
|
||||
if (!userId) {
|
||||
log.warn("Authentication required but rejected");
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
Reference in New Issue
Block a user