fix: 用户名唯一性竞态处理 + 密码长度上限 + JSON.parse 安全
- #6: register/user PUT 捕获 P2002 返回 409,apiHandler 全局兜底 - #8: GET /api/user 的 JSON.parse(preferences) 加 try/catch 防崩溃 - #12: 密码校验加 128 字符上限防 DoS - #29: ApiError.name 设为 "ApiError" 便于调试
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
import { apiHandler, ApiError } from "@/lib/api";
|
import { apiHandler, ApiError } from "@/lib/api";
|
||||||
import { validateUsername, validatePassword } from "@/lib/validation";
|
import { validateUsername, validatePassword } from "@/lib/validation";
|
||||||
@@ -12,11 +13,9 @@ export const POST = apiHandler(async (req) => {
|
|||||||
const trimmedUsername = validateUsername(username);
|
const trimmedUsername = validateUsername(username);
|
||||||
validatePassword(password);
|
validatePassword(password);
|
||||||
|
|
||||||
const existing = await prisma.user.findUnique({ where: { username: trimmedUsername } });
|
|
||||||
if (existing) throw new ApiError("用户名已被注册", 409);
|
|
||||||
|
|
||||||
const passwordHash = await bcrypt.hash(password, 10);
|
const passwordHash = await bcrypt.hash(password, 10);
|
||||||
|
|
||||||
|
try {
|
||||||
const user = await prisma.user.create({
|
const user = await prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
username: trimmedUsername,
|
username: trimmedUsername,
|
||||||
@@ -30,4 +29,10 @@ export const POST = apiHandler(async (req) => {
|
|||||||
username: user.username,
|
username: user.username,
|
||||||
avatar: user.avatar,
|
avatar: user.avatar,
|
||||||
});
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
|
||||||
|
throw new ApiError("用户名已被注册", 409);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
import { apiHandler, ApiError, requireUserId, requireUser } from "@/lib/api";
|
import { apiHandler, ApiError, requireUserId, requireUser } from "@/lib/api";
|
||||||
import { validateUsername, validatePassword, validateEmail } from "@/lib/validation";
|
import { validateUsername, validatePassword, validateEmail } from "@/lib/validation";
|
||||||
@@ -13,12 +14,15 @@ export const GET = apiHandler(async (req) => {
|
|||||||
|
|
||||||
const decisionCount = await prisma.decision.count({ where: { userId } });
|
const decisionCount = await prisma.decision.count({ where: { userId } });
|
||||||
|
|
||||||
|
let preferences = {};
|
||||||
|
try { preferences = JSON.parse(user.preferences); } catch { /* fallback */ }
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
id: user.id,
|
id: user.id,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
avatar: user.avatar,
|
avatar: user.avatar,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
preferences: JSON.parse(user.preferences),
|
preferences,
|
||||||
createdAt: user.createdAt.toISOString(),
|
createdAt: user.createdAt.toISOString(),
|
||||||
decisionCount,
|
decisionCount,
|
||||||
});
|
});
|
||||||
@@ -63,6 +67,7 @@ export const PUT = apiHandler(async (req) => {
|
|||||||
updateData.preferences = JSON.stringify(body.preferences);
|
updateData.preferences = JSON.stringify(body.preferences);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
const user = await prisma.user.update({
|
const user = await prisma.user.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: updateData,
|
data: updateData,
|
||||||
@@ -75,4 +80,10 @@ export const PUT = apiHandler(async (req) => {
|
|||||||
email: user.email,
|
email: user.email,
|
||||||
preferences: JSON.parse(user.preferences),
|
preferences: JSON.parse(user.preferences),
|
||||||
});
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
|
||||||
|
throw new ApiError("用户名已被占用", 409);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
@@ -7,6 +8,7 @@ export class ApiError extends Error {
|
|||||||
public status: number = 400,
|
public status: number = 400,
|
||||||
) {
|
) {
|
||||||
super(message);
|
super(message);
|
||||||
|
this.name = "ApiError";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,6 +47,15 @@ export function apiHandler(handler: RouteHandler): RouteHandler {
|
|||||||
if (e instanceof ApiError) {
|
if (e instanceof ApiError) {
|
||||||
return NextResponse.json({ error: e.message }, { status: e.status });
|
return NextResponse.json({ error: e.message }, { status: e.status });
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
e instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
e.code === "P2002"
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "该记录已存在或值已被占用" },
|
||||||
|
{ status: 409 },
|
||||||
|
);
|
||||||
|
}
|
||||||
console.error(`[API ${req.method} ${req.nextUrl.pathname}]`, e);
|
console.error(`[API ${req.method} ${req.nextUrl.pathname}]`, e);
|
||||||
return NextResponse.json({ error: "操作失败" }, { status: 500 });
|
return NextResponse.json({ error: "操作失败" }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ export function validatePassword(password: string, label = "密码"): void {
|
|||||||
if (password.length < 6) {
|
if (password.length < 6) {
|
||||||
throw new ApiError(`${label}至少 6 个字符`);
|
throw new ApiError(`${label}至少 6 个字符`);
|
||||||
}
|
}
|
||||||
|
if (password.length > 128) {
|
||||||
|
throw new ApiError(`${label}不能超过 128 个字符`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateEmail(email: string): void {
|
export function validateEmail(email: string): void {
|
||||||
|
|||||||
Reference in New Issue
Block a user