mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-02 07:30:03 +08:00
refactor: error-items 路由改用 withUser 统一鉴权
将 error-items 领域全部 19 个路由的样板鉴权代码(getServerSession / getCurrentUser → 查用户 → 401)替换为 withUser 包装器: - 删除 getServerSession、getCurrentUser、authOptions 的 import 和调用 - 删除 prisma.user.findUnique 查用户和 if (!user) return unauthorized 判空 - 删除鉴权专用的 try/catch 层 - 已有 withRecoverableResponse 的路由保持组合方式不变(外层) - 保留所有业务 try/catch 及特定错误文案/状态码 测试中允许的文案断言修改: - stats.test.ts 中 DELETE /api/error-items/clear 的 401 文案 从 'Unauthorized' 统一为 'Authentication required' - stats.test.ts 补充 mockPrismaUser(withUser 内部需要 prisma.user.findUnique)
This commit is contained in:
@@ -6,6 +6,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Use vi.hoisted to ensure mocks are initialized before module imports
|
||||
const mocks = vi.hoisted(() => ({
|
||||
mockPrismaUser: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
mockPrismaPracticeRecord: {
|
||||
groupBy: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
@@ -32,10 +35,10 @@ const mocks = vi.hoisted(() => ({
|
||||
// Mock Prisma client
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
user: mocks.mockPrismaUser,
|
||||
practiceRecord: mocks.mockPrismaPracticeRecord,
|
||||
errorItem: mocks.mockPrismaErrorItem,
|
||||
subject: mocks.mockPrismaSubject,
|
||||
user: { findUnique: vi.fn(async () => ({ id: 'user-123', email: 'user@example.com', masteryThreshold: 50 })) },
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -64,6 +67,12 @@ describe('/api/stats', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getServerSession).mockResolvedValue(mocks.mockSession);
|
||||
mocks.mockPrismaUser.findUnique.mockResolvedValue({
|
||||
id: 'user-123',
|
||||
email: 'user@example.com',
|
||||
name: 'Test User',
|
||||
masteryThreshold: 50,
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/stats/practice (获取练习统计)', () => {
|
||||
@@ -682,7 +691,7 @@ describe('/api/stats', () => {
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(data.message).toBe('Unauthorized');
|
||||
expect(data.message).toBe('Authentication required');
|
||||
});
|
||||
|
||||
it('应该拒绝 session 中没有 user 的请求', async () => {
|
||||
@@ -696,7 +705,7 @@ describe('/api/stats', () => {
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(data.message).toBe('Unauthorized');
|
||||
expect(data.message).toBe('Authentication required');
|
||||
});
|
||||
|
||||
it('应该处理数据库错误', async () => {
|
||||
|
||||
@@ -1,31 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, forbidden, notFound, internalError } from "@/lib/api-errors";
|
||||
import { forbidden, notFound, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const logger = createLogger('api:error-items:delete');
|
||||
|
||||
export async function DELETE(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
export const DELETE = withUser(async (_req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
// Verify ownership before deletion
|
||||
const errorItem = await prisma.errorItem.findUnique({
|
||||
where: { id: id },
|
||||
@@ -49,4 +36,4 @@ export async function DELETE(
|
||||
logger.error({ error }, 'Error deleting item');
|
||||
return internalError("Failed to delete error item");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { consumeAiQuota } from "@/lib/ai-quota";
|
||||
@@ -10,22 +11,19 @@ import { withRecoverableResponse } from "@/lib/recoverable-response";
|
||||
|
||||
const logger = createLogger('api:error-items:figure');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* POST /api/error-items/:id/figure
|
||||
* 用原题图片让 AI 重新判断是否有配图,并重绘 SVG 配图后保存
|
||||
*/
|
||||
async function handlePost(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ user, params }: RouteContext & AuthenticatedContext
|
||||
) {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await prisma.errorItem.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true, shortId: true, originalImageUrl: true, questionText: true },
|
||||
@@ -66,4 +64,4 @@ async function handlePost(
|
||||
}
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -2,8 +2,9 @@ import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
import type { LatexFixInput } from "@/lib/ai";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, internalError } from "@/lib/api-errors";
|
||||
import { notFound, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { countLatexIssues, findLatexIssuesByField, isAcceptableLatexFix, LATEX_FIELDS } from "@/lib/latex-check";
|
||||
@@ -13,6 +14,8 @@ import { withRecoverableResponse } from "@/lib/recoverable-response";
|
||||
|
||||
const logger = createLogger('api:error-items:fix-latex');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* POST /api/error-items/:id/fix-latex
|
||||
* 用 KaTeX 检查题目、答案、解析、错误解答和错因分析中的 LaTeX,只把有问题的字段交给 AI 修复;
|
||||
@@ -20,16 +23,11 @@ const logger = createLogger('api:error-items:fix-latex');
|
||||
*/
|
||||
async function handlePost(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ user, params }: RouteContext & AuthenticatedContext
|
||||
) {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await prisma.errorItem.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true, shortId: true, questionText: true, answerText: true, analysis: true, wrongAnswerText: true, mistakeAnalysis: true },
|
||||
@@ -85,4 +83,4 @@ async function handlePost(
|
||||
}
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, forbidden, notFound, internalError } from "@/lib/api-errors";
|
||||
import { forbidden, notFound, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
@@ -11,25 +11,15 @@ import { withRecoverableResponse } from "@/lib/recoverable-response";
|
||||
|
||||
const logger = createLogger('api:error-items:geogebra');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
async function handlePost(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ user, params }: RouteContext & AuthenticatedContext
|
||||
) {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const errorItem = await prisma.errorItem.findUnique({
|
||||
where: { id },
|
||||
include: { subject: true },
|
||||
@@ -117,21 +107,10 @@ async function handlePost(
|
||||
* DELETE /api/error-items/:id/geogebra
|
||||
* 删除已生成的 GeoGebra 演示命令
|
||||
*/
|
||||
export async function DELETE(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
export const DELETE = withUser(async (_req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
const user = session?.user?.email
|
||||
? await prisma.user.findUnique({ where: { email: session.user.email } })
|
||||
: null;
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const errorItem = await prisma.errorItem.findUnique({ where: { id }, select: { userId: true } });
|
||||
if (!errorItem) {
|
||||
return notFound("Item not found");
|
||||
@@ -147,7 +126,7 @@ export async function DELETE(
|
||||
logger.error({ error }, 'Error deleting GeoGebra commands');
|
||||
return internalError("Failed to delete GeoGebra commands");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const logger = createLogger('api:error-items:image');
|
||||
@@ -19,23 +20,17 @@ const bodySchema = z.object({
|
||||
/** 允许直接输出的原图类型;不输出 SVG 等可执行脚本的格式 */
|
||||
const SERVABLE_IMAGE = /^data:(image\/(?:png|jpe?g|webp|gif));base64,([\s\S]+)$/;
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* GET /api/error-items/:id/image
|
||||
* 以二进制图片输出原题图片,供打印预览按需懒加载,避免列表接口携带大段 base64。
|
||||
* 链接带 `?v=<更新时间>`,原图替换后链接随之变化,因此可长期缓存。
|
||||
*/
|
||||
export async function GET(
|
||||
_req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
export const GET = withUser(async (_req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await prisma.errorItem.findUnique({ where: { id }, select: { userId: true, originalImageUrl: true } });
|
||||
if (!item || item.userId !== user.id) {
|
||||
return notFound("Item not found");
|
||||
@@ -59,24 +54,16 @@ export async function GET(
|
||||
logger.error({ error }, 'Error reading original image');
|
||||
return internalError("Failed to read image");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* PUT /api/error-items/:id/image
|
||||
* 替换(或补充)原题图片;题目文字、配图等其他内容不变
|
||||
*/
|
||||
export async function PUT(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
export const PUT = withUser(async (req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return badRequest("INVALID_IMAGE");
|
||||
@@ -94,4 +81,4 @@ export async function PUT(
|
||||
logger.error({ error }, 'Error replacing original image');
|
||||
return internalError("Failed to replace image");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,31 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const logger = createLogger('api:error-items:notes');
|
||||
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
export const PATCH = withUser(async (req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const { userNotes } = await req.json();
|
||||
if (userNotes !== null && typeof userNotes !== 'string') {
|
||||
return badRequest("userNotes must be a string");
|
||||
@@ -50,4 +37,4 @@ export async function PATCH(
|
||||
logger.error({ error }, 'Error updating notes');
|
||||
return internalError("Failed to update notes");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,28 +1,23 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, forbidden, notFound, internalError } from "@/lib/api-errors";
|
||||
import { forbidden, notFound, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { masteryStatusOf } from "@/lib/mastery-status";
|
||||
|
||||
const logger = createLogger('api:error-items:practice-records');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* GET /api/error-items/:id/practice-records
|
||||
* 返回错题的掌握概率与举一反三历史(按时间倒序)
|
||||
*/
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
export const GET = withUser(async (_req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await prisma.errorItem.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
@@ -77,4 +72,4 @@ export async function GET(
|
||||
logger.error({ error }, 'Error fetching practice records');
|
||||
return internalError("Failed to fetch practice records");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { resolveNotebookScope, SUBJECT_DISPLAY_NAMES } from "@/lib/notebook-scope";
|
||||
@@ -11,6 +12,8 @@ import { withRecoverableResponse } from "@/lib/recoverable-response";
|
||||
|
||||
const logger = createLogger('api:error-items:reanswer');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* POST /api/error-items/:id/reanswer
|
||||
* 根据题目文字(有原图时一并提供)让 AI 重新生成完整的答案和解析并保存;
|
||||
@@ -18,16 +21,11 @@ const logger = createLogger('api:error-items:reanswer');
|
||||
*/
|
||||
async function handlePost(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ user, params }: RouteContext & AuthenticatedContext
|
||||
) {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await prisma.errorItem.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
@@ -80,4 +78,4 @@ async function handlePost(
|
||||
}
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { previewRetagErrorItem, retagErrorItem } from "@/lib/retag";
|
||||
@@ -10,6 +11,8 @@ import { withRecoverableResponse } from "@/lib/recoverable-response";
|
||||
|
||||
const logger = createLogger('api:error-items:retag');
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
/**
|
||||
* POST /api/error-items/:id/retag
|
||||
* 用 AI 从当前知识点库中重新选取本题的知识点(替换系统标签,保留自定义标签)
|
||||
@@ -17,16 +20,11 @@ const logger = createLogger('api:error-items:retag');
|
||||
*/
|
||||
async function handlePost(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
{ user, params }: RouteContext & AuthenticatedContext
|
||||
) {
|
||||
const { id } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => ({})) as { preview?: unknown };
|
||||
const item = await prisma.errorItem.findUnique({ where: { id }, select: { userId: true, shortId: true, questionText: true } });
|
||||
if (!item || item.userId !== user.id) {
|
||||
@@ -55,4 +53,4 @@ async function handlePost(
|
||||
}
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, forbidden, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { forbidden, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { resolveOrCreateTags, inferTagScope } from "@/lib/tag-resolver";
|
||||
import { normalizeMistakeStatusForSave } from "@/lib/mistake-status";
|
||||
@@ -12,25 +12,12 @@ import { isValidFigureAlign, isValidFigureScale } from "@/lib/figure-scale";
|
||||
|
||||
const logger = createLogger('api:error-items:id');
|
||||
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
export const GET = withUser(async (_req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const errorItem = await prisma.errorItem.findUnique({
|
||||
where: {
|
||||
id: id,
|
||||
@@ -55,27 +42,12 @@ export async function GET(
|
||||
logger.error({ error }, 'Error fetching item');
|
||||
return internalError("Failed to fetch error item");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function PUT(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
export const PUT = withUser(async (req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const { knowledgePoints, gradeSemester, paperLevel, questionText, answerText, analysis, subjectId, wrongAnswerText, mistakeAnalysis, mistakeStatus, geogebraCommands, difficultyStars } = body;
|
||||
const { figureScale, figureAlign } = body;
|
||||
@@ -196,4 +168,4 @@ export async function PUT(
|
||||
logger.error({ error }, 'Error updating item');
|
||||
return internalError("Failed to update error item");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { consumeAiQuota } from "@/lib/ai-quota";
|
||||
@@ -18,18 +19,13 @@ type RouteContext = { params: Promise<{ id: string }> };
|
||||
* 由 AI 为已生成的动画补写语音讲解稿,写入动画 SVG 后保存,画面不变(替换已有的讲解稿)
|
||||
* 请求体 { language: 'zh' | 'en' }:处理该语言的动画,讲解使用该语言,未指定时为中文
|
||||
*/
|
||||
async function handlePost(req: Request, { params }: RouteContext) {
|
||||
async function handlePost(req: Request, { user, params }: RouteContext & AuthenticatedContext) {
|
||||
const { id } = await params;
|
||||
const body = await req.json().catch(() => ({})) as { language?: unknown };
|
||||
const language = body.language === 'en' ? 'en' : 'zh';
|
||||
const field = language === 'en' ? 'svgAnimationEn' : 'svgAnimation';
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await prisma.errorItem.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true, shortId: true, questionText: true, answerText: true, analysis: true, svgAnimation: true, svgAnimationEn: true },
|
||||
@@ -73,4 +69,4 @@ async function handlePost(req: Request, { params }: RouteContext) {
|
||||
}
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { consumeAiQuota } from "@/lib/ai-quota";
|
||||
@@ -36,17 +37,12 @@ async function findOwnedItem(id: string, userId: string) {
|
||||
* 由 AI 根据题目、答案和解析生成 SVG 动画讲解并保存(覆盖该语言已有的动画)
|
||||
* 请求体 { language: 'zh' | 'en' }:动画中的文字使用该语言,未指定时为中文
|
||||
*/
|
||||
async function handlePost(req: Request, { params }: RouteContext) {
|
||||
async function handlePost(req: Request, { user, params }: RouteContext & AuthenticatedContext) {
|
||||
const { id } = await params;
|
||||
const body = await req.json().catch(() => ({})) as { language?: unknown };
|
||||
const language = parseLanguage(body.language);
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const item = await findOwnedItem(id, user.id);
|
||||
if (!item) {
|
||||
return notFound("Item not found");
|
||||
@@ -90,15 +86,11 @@ async function handlePost(req: Request, { params }: RouteContext) {
|
||||
* DELETE /api/error-items/:id/svg-animation?language=zh|en
|
||||
* 删除指定语言已生成的 SVG 动画讲解,另一语言的动画保留;未指定时为中文
|
||||
*/
|
||||
export async function DELETE(req: Request, { params }: RouteContext) {
|
||||
export const DELETE = withUser(async (req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { id } = await params;
|
||||
const language = parseLanguage(new URL(req.url).searchParams.get('language'));
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
if (!await findOwnedItem(id, user.id)) {
|
||||
return notFound("Item not found");
|
||||
}
|
||||
@@ -110,7 +102,7 @@ export async function DELETE(req: Request, { params }: RouteContext) {
|
||||
logger.error({ error }, 'Error deleting SVG animation');
|
||||
return internalError("Failed to delete SVG animation");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** 耗时 AI 请求:浏览器中断连接后,前端可通过 /api/requests/:id 取回响应 */
|
||||
export const POST = withRecoverableResponse(handlePost);
|
||||
export const POST = withRecoverableResponse(withUser(handlePost));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, validationError, internalError } from "@/lib/api-errors";
|
||||
import { validationError, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { PRINT_PREVIEW_PAGE_SIZE } from "@/lib/constants/pagination";
|
||||
import { MAX_CUSTOM_ANSWER_SPACE_PX, MIN_CUSTOM_ANSWER_SPACE_PX } from "@/lib/exam-answer-space";
|
||||
@@ -21,13 +22,8 @@ const answerSpaceSchema = z.object({
|
||||
* PUT /api/error-items/answer-space
|
||||
* 批量保存错题打印时手动调整的题下留白高度;只更新当前用户自己的错题
|
||||
*/
|
||||
export async function PUT(req: Request) {
|
||||
export const PUT = withUser(async (req: Request, { user }: AuthenticatedContext) => {
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const parsed = answerSpaceSchema.safeParse(await req.json().catch(() => ({})));
|
||||
if (!parsed.success) {
|
||||
return validationError("Invalid answer space settings", parsed.error.issues);
|
||||
@@ -50,4 +46,4 @@ export async function PUT(req: Request) {
|
||||
logger.error({ error }, 'Error saving answer space');
|
||||
return internalError("Failed to save answer space");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { badRequest, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const logger = createLogger('api:error-items:batch-delete');
|
||||
@@ -12,11 +12,9 @@ const logger = createLogger('api:error-items:batch-delete');
|
||||
* 批量删除错题
|
||||
* Body: { ids: string[] }
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
export const POST = withUser(async (req: Request, { user }: AuthenticatedContext) => {
|
||||
logger.info('POST /api/error-items/batch-delete called');
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { ids } = body;
|
||||
@@ -30,18 +28,6 @@ export async function POST(req: Request) {
|
||||
return badRequest("Cannot delete more than 100 items at once");
|
||||
}
|
||||
|
||||
// 验证用户身份
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
logger.debug({ userId: user.id, idsCount: ids.length }, 'Batch delete request');
|
||||
|
||||
// 查询所有要删除的错题,验证所有权
|
||||
@@ -87,4 +73,4 @@ export async function POST(req: Request) {
|
||||
logger.error({ error }, 'Error in batch delete');
|
||||
return internalError("Failed to delete items");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, internalError } from "@/lib/api-errors";
|
||||
import { internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const logger = createLogger('api:error-items:clear');
|
||||
|
||||
export async function DELETE() {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session || !session.user) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
|
||||
export const DELETE = withUser(async (_req: Request, { user }: AuthenticatedContext) => {
|
||||
try {
|
||||
// Delete all error items for this user
|
||||
await prisma.errorItem.deleteMany({
|
||||
where: { userId }
|
||||
where: { userId: user.id }
|
||||
});
|
||||
|
||||
return NextResponse.json({ message: "Error data cleared successfully" });
|
||||
@@ -27,4 +19,4 @@ export async function DELETE() {
|
||||
logger.error({ error }, 'Error clearing error data');
|
||||
return internalError("Failed to clear error data");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { unauthorized, internalError } from "@/lib/api-errors";
|
||||
import { internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { ERROR_ITEM_LIST_SELECT, ERROR_ITEM_PRINT_SELECT, printImageUrl } from "@/lib/error-list-select";
|
||||
import { parseErrorListQueryParams, buildErrorListWhere } from "@/lib/error-list-query";
|
||||
@@ -11,24 +11,11 @@ import { masteryStatusOf } from "@/lib/mastery-status";
|
||||
|
||||
const logger = createLogger('api:error-items:list');
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
export const GET = withUser(async (req: Request, { user }: AuthenticatedContext) => {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const params = parseErrorListQueryParams(searchParams);
|
||||
|
||||
try {
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const whereClause = await buildErrorListWhere(params, user.id, user.masteryThreshold, prisma);
|
||||
|
||||
// 获取总数
|
||||
@@ -58,7 +45,7 @@ export async function GET(req: Request) {
|
||||
logger.error({ error }, 'Error fetching items');
|
||||
return internalError("Failed to fetch error items");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 打印视图:读取解答与配图;base64 原图换成懒加载的图片接口链接,外部链接原样返回。
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { authOptions } from "@/lib/auth";
|
||||
import { unauthorized, validationError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { validationError } from "@/lib/api-errors";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { importSchema, saveQuestionForUser } from "@/lib/question-save";
|
||||
import { questionSaveErrorResponse } from "@/lib/question-save-error-response";
|
||||
|
||||
const logger = createLogger('api:error-items');
|
||||
|
||||
export async function POST(req: Request) {
|
||||
export const POST = withUser(async (req: Request, { user }: AuthenticatedContext) => {
|
||||
logger.info('POST /api/error-items called');
|
||||
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
const parsed = importSchema.safeParse(await req.json());
|
||||
if (!parsed.success) return validationError('QUESTION_SAVE_INVALID_INPUT', parsed.error.issues);
|
||||
const body = parsed.data;
|
||||
@@ -35,22 +33,6 @@ export async function POST(req: Request) {
|
||||
hasGeogebraCommands: !!body.geogebraCommands,
|
||||
}, 'Request parameters received');
|
||||
|
||||
// 查找用户
|
||||
let user;
|
||||
if (session?.user?.email) {
|
||||
user = await prisma.user.findUnique({
|
||||
where: { email: session.user.email },
|
||||
});
|
||||
logger.debug({ userId: user?.id, email: session.user.email }, 'User lookup result');
|
||||
} else {
|
||||
logger.warn('No session email found');
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
logger.warn({ sessionEmail: session?.user?.email }, 'User not found in DB');
|
||||
return unauthorized("No user found in DB");
|
||||
}
|
||||
|
||||
return await saveQuestionForUser(user, body);
|
||||
} catch (error) {
|
||||
logger.error({
|
||||
@@ -60,4 +42,4 @@ export async function POST(req: Request) {
|
||||
}, 'Error saving item');
|
||||
return questionSaveErrorResponse(error);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getCurrentUser } from "@/lib/current-user";
|
||||
import { unauthorized, notFound, internalError } from "@/lib/api-errors";
|
||||
import { notFound, internalError } from "@/lib/api-errors";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { isShortId } from "@/lib/short-id";
|
||||
|
||||
const logger = createLogger('api:error-items:short');
|
||||
|
||||
type RouteContext = { params: Promise<{ shortId: string }> };
|
||||
|
||||
/**
|
||||
* GET /api/error-items/short/:shortId
|
||||
* 按短 ID 定位当前用户的题目
|
||||
*/
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ shortId: string }> }
|
||||
) {
|
||||
export const GET = withUser(async (_req: Request, { user, params }: RouteContext & AuthenticatedContext) => {
|
||||
const { shortId } = await params;
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) {
|
||||
return unauthorized("Authentication required");
|
||||
}
|
||||
if (!isShortId(shortId)) {
|
||||
return notFound("Item not found");
|
||||
}
|
||||
@@ -39,4 +35,4 @@ export async function GET(
|
||||
logger.error({ error }, 'Error locating item by short ID');
|
||||
return internalError("Failed to locate error item");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { badRequest, internalError, notFound, unauthorized, validationError } from '@/lib/api-errors';
|
||||
import { getCurrentUser } from '@/lib/current-user';
|
||||
import { badRequest, internalError, notFound, validationError } from '@/lib/api-errors';
|
||||
import { withUser } from '@/lib/api-handler';
|
||||
import type { AuthenticatedContext } from '@/lib/api-handler';
|
||||
import { createLogger } from '@/lib/logger';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { calculateQuestionSimilarity, DEFAULT_QUESTION_DUPLICATE_THRESHOLD, duplicateQuestionSimilarity } from '@/lib/question-similarity';
|
||||
@@ -11,10 +12,8 @@ const schema = z.object({ ids: z.tuple([z.string().min(1).max(200), z.string().m
|
||||
.refine(({ ids }) => ids[0] !== ids[1], { message: 'Select two different questions' });
|
||||
|
||||
/** 只比较当前用户的两道题,使用与自动导入相同的相似度定义,不写入练习记录。 */
|
||||
export async function POST(req: Request) {
|
||||
export const POST = withUser(async (req: Request, { user }: AuthenticatedContext) => {
|
||||
try {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) return unauthorized();
|
||||
const parsed = schema.safeParse(await req.json());
|
||||
if (!parsed.success) return validationError('Invalid question selection', parsed.error.issues);
|
||||
const items = await prisma.errorItem.findMany({
|
||||
@@ -37,4 +36,4 @@ export async function POST(req: Request) {
|
||||
logger.error({ error }, '相似度比较失败');
|
||||
return internalError('Failed to compare questions');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user