diff --git a/app/api/auth/register/route.ts b/app/api/auth/register/route.ts index 81cc216..18c2513 100644 --- a/app/api/auth/register/route.ts +++ b/app/api/auth/register/route.ts @@ -1,25 +1,28 @@ +import { NextResponse } from "next/server" import { register } from "@/lib/auth" -import { authSchema } from "@/lib/validation" -import { ZodError } from "zod" +import { authSchema, AuthSchema } from "@/lib/validation" export const runtime = "edge" export async function POST(request: Request) { try { - const json = await request.json() - const body = authSchema.parse(json) - - await register(body.username, body.password) - return Response.json({ success: true }) - } catch (error) { - if (error instanceof ZodError) { - return Response.json( - { error: error.errors[0].message }, + const json = await request.json() as AuthSchema + + try { + authSchema.parse(json) + } catch (error) { + return NextResponse.json( + { error: error instanceof Error ? error.message : "输入格式不正确" }, { status: 400 } ) } - return Response.json( + const { username, password } = json + const user = await register(username, password) + + return NextResponse.json({ user }) + } catch (error) { + return NextResponse.json( { error: error instanceof Error ? error.message : "注册失败" }, { status: 500 } ) diff --git a/app/components/auth/login-form.tsx b/app/components/auth/login-form.tsx index bde56d6..eaf9f15 100644 --- a/app/components/auth/login-form.tsx +++ b/app/components/auth/login-form.tsx @@ -39,6 +39,7 @@ export function LoginForm() { const newErrors: FormErrors = {} if (!username) newErrors.username = "请输入用户名" if (!password) newErrors.password = "请输入密码" + if (username.includes('@')) newErrors.username = "用户名不能包含 @ 符号" if (password && password.length < 8) newErrors.password = "密码长度必须大于等于8位" setErrors(newErrors) return Object.keys(newErrors).length === 0 @@ -48,6 +49,7 @@ export function LoginForm() { const newErrors: FormErrors = {} if (!username) newErrors.username = "请输入用户名" if (!password) newErrors.password = "请输入密码" + if (username.includes('@')) newErrors.username = "用户名不能包含 @ 符号" if (password && password.length < 8) newErrors.password = "密码长度必须大于等于8位" if (!confirmPassword) newErrors.confirmPassword = "请确认密码" if (password !== confirmPassword) newErrors.confirmPassword = "两次输入的密码不一致" diff --git a/app/lib/validation.ts b/app/lib/validation.ts index 2f6989e..a4ab401 100644 --- a/app/lib/validation.ts +++ b/app/lib/validation.ts @@ -1,8 +1,13 @@ import { z } from "zod" export const authSchema = z.object({ - username: z.string().min(1, "用户名不能为空"), - password: z.string().min(8, "密码长度必须大于等于8位"), + username: z.string() + .min(1, "用户名不能为空") + .max(20, "用户名不能超过20个字符") + .regex(/^[a-zA-Z0-9_-]+$/, "用户名只能包含字母、数字、下划线和横杠") + .refine(val => !val.includes('@'), "用户名不能是邮箱格式"), + password: z.string() + .min(8, "密码长度必须大于等于8位") }) export type AuthSchema = z.infer \ No newline at end of file