From c7f791cf5571a20e74a83cf11efe91ff4a6246ea Mon Sep 17 00:00:00 2001 From: npmrun <1549469775@qq.com> Date: Fri, 15 May 2026 10:47:50 +0800 Subject: [PATCH] feat: add POST /api/auth/register endpoint Co-Authored-By: Claude Opus 4.7 --- server/api/auth/register.post.ts | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 server/api/auth/register.post.ts diff --git a/server/api/auth/register.post.ts b/server/api/auth/register.post.ts new file mode 100644 index 0000000..24549dd --- /dev/null +++ b/server/api/auth/register.post.ts @@ -0,0 +1,43 @@ +import { registerSchema } from '../../utils/auth/validation' +import { verifyCaptcha } from '../../utils/auth/captcha' +import { dbGlobal } from 'drizzle-pkg/lib/db' +import { users } from 'drizzle-pkg/lib/schema/auth' +import { eq } from 'drizzle-orm' +import { hash } from 'bcryptjs' + +export default defineWrappedResponseHandler(async (event) => { + const body = await readBody(event) + + const parsed = registerSchema.safeParse(body) + if (!parsed.success) { + return R.error(parsed.error.issues[0]?.message || '表单验证失败', null) + } + + const { username, password, captchaToken, captchaText } = parsed.data + + if (!verifyCaptcha(captchaToken, captchaText)) { + return R.error('验证码错误或已过期', null) + } + + const existing = await dbGlobal + .select() + .from(users) + .where(eq(users.username, username)) + if (existing.length > 0) { + return R.error('用户名已存在', null) + } + + const hashedPassword = await hash(password, 10) + + const result = await dbGlobal + .insert(users) + .values({ + username, + password: hashedPassword, + role: 'user', + status: 'active', + }) + .returning({ id: users.id }) + + return R.success({ id: result[0].id, username }) +})