You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

47 lines
1.5 KiB

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 { hash } from 'bcryptjs'
import log4js from 'logger'
const logger = log4js.getLogger('AUTH')
export default defineWrappedResponseHandler(async (event) => {
const body = await readBody(event)
const parsed = registerSchema.safeParse(body)
if (!parsed.success) {
const field = parsed.error.issues[0]?.path[0]?.toString() ?? undefined
return R.error(parsed.error.issues[0]?.message || '表单验证失败', { field })
}
const { username, password, captchaToken, captchaText } = parsed.data
if (!verifyCaptcha(captchaToken, captchaText)) {
return R.error('验证码错误或已过期', { field: 'captchaText' })
}
const hashedPassword = await hash(password, 10)
try {
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 })
} catch (err: any) {
const msg = String(err?.message ?? '')
if (msg.toLowerCase().includes('unique') || msg.includes('SQLITE_CONSTRAINT')) {
return R.error('用户名已存在', { field: 'username' })
}
logger.error('Failed to insert user', msg)
return R.error('注册失败,请稍后重试', null)
}
})