refactor: 提取 validation.ts 和 amap.ts,统一 API 路由校验逻辑
新增 validation.ts(用户名/密码/邮箱/内容/房间名/必填字段校验) 和 amap.ts(AMAP API key 校验),消除 7 个路由中的重复验证代码。
This commit is contained in:
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { apiHandler, ApiError, requireUserId, requireUser } from "@/lib/api";
|
||||
import { validateUsername, validatePassword, validateEmail } from "@/lib/validation";
|
||||
|
||||
export const GET = apiHandler(async (req) => {
|
||||
const userId = req.nextUrl.searchParams.get("id");
|
||||
@@ -33,10 +34,7 @@ export const PUT = apiHandler(async (req) => {
|
||||
const updateData: Record<string, unknown> = {};
|
||||
|
||||
if (body.username !== undefined) {
|
||||
const trimmed = body.username.trim();
|
||||
if (trimmed.length < 2 || trimmed.length > 16) {
|
||||
throw new ApiError("用户名需要 2-16 个字符");
|
||||
}
|
||||
const trimmed = validateUsername(body.username);
|
||||
if (trimmed !== existing.username) {
|
||||
const taken = await prisma.user.findUnique({ where: { username: trimmed } });
|
||||
if (taken) throw new ApiError("用户名已被占用", 409);
|
||||
@@ -48,7 +46,7 @@ export const PUT = apiHandler(async (req) => {
|
||||
if (!body.currentPassword) throw new ApiError("请输入当前密码");
|
||||
const valid = await bcrypt.compare(body.currentPassword, existing.passwordHash);
|
||||
if (!valid) throw new ApiError("当前密码错误", 403);
|
||||
if (body.newPassword.length < 6) throw new ApiError("新密码至少 6 个字符");
|
||||
validatePassword(body.newPassword, "新密码");
|
||||
updateData.passwordHash = await bcrypt.hash(body.newPassword, 10);
|
||||
}
|
||||
|
||||
@@ -57,9 +55,7 @@ export const PUT = apiHandler(async (req) => {
|
||||
}
|
||||
|
||||
if (body.email !== undefined) {
|
||||
if (body.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.email)) {
|
||||
throw new ApiError("邮箱格式不正确");
|
||||
}
|
||||
if (body.email) validateEmail(body.email);
|
||||
updateData.email = body.email || null;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user