Files
no-whatever/src/app/api/user/favorite/route.ts
T
kurihada ce76980fe5 refactor(P0): JWT 认证、并发安全、错误日志三项安全加固
- 新增 JWT httpOnly cookie 认证链路 (jose),登录/注册签发 token,
  所有用户和盲盒 API 改为从 cookie 提取 userId,不再信任客户端传值
- 新增 /api/auth/logout 端点清除认证 cookie
- GET /api/user 区分 owner/非 owner,非 owner 不暴露 email
- atomicUpdateRoom 新增 per-room 应用层互斥锁,防止 SQLite 下并发 lost update
- 修复 getRoomData 中 fire-and-forget delete 改为 await
- 37 个静默 catch 块跨 17 个文件添加 console.error 日志
- 新增 REFACTOR_PLAN.md 全景分析文档
2026-03-02 17:24:26 +08:00

67 lines
2.0 KiB
TypeScript

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { apiHandler, ApiError, requireUser } from "@/lib/api";
import { getAuthUserId } from "@/lib/auth";
export const GET = apiHandler(async (req) => {
const userId = await getAuthUserId(req);
const favorites = await prisma.favorite.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
take: 50,
});
return NextResponse.json(
favorites.map((f) => {
let restaurantData = {};
try { restaurantData = JSON.parse(f.restaurantData); } catch { /* ignore */ }
return { id: f.id, restaurantData, createdAt: f.createdAt.toISOString() };
}),
);
});
export const POST = apiHandler(async (req) => {
const userId = await getAuthUserId(req);
const { restaurant } = await req.json();
if (!restaurant?.id || typeof restaurant.id !== "string") {
throw new ApiError("缺少必要字段");
}
await requireUser(userId);
try {
const fav = await prisma.favorite.create({
data: {
userId,
restaurantId: restaurant.id,
restaurantData: JSON.stringify(restaurant),
},
});
return NextResponse.json({ id: fav.id });
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
const existing = await prisma.favorite.findFirst({
where: { userId, restaurantId: restaurant.id },
});
return NextResponse.json({ id: existing?.id ?? "", alreadyExists: true });
}
throw e;
}
});
export const DELETE = apiHandler(async (req) => {
const userId = await getAuthUserId(req);
const { favoriteId } = await req.json();
if (!favoriteId) throw new ApiError("缺少必要字段");
const fav = await prisma.favorite.findUnique({ where: { id: favoriteId } });
if (!fav || fav.userId !== userId) throw new ApiError("收藏不存在", 404);
await prisma.favorite.delete({ where: { id: favoriteId } });
return NextResponse.json({ ok: true });
});