|
|
@@ -0,0 +1,95 @@
|
|
|
+import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
|
|
|
+import { AuthService } from '../../../modules/auth/auth.service'
|
|
|
+import { UserService } from '../../../modules/users/user.service'
|
|
|
+import { z } from '@hono/zod-openapi'
|
|
|
+import { AppDataSource } from '../../../data-source'
|
|
|
+import { ErrorSchema } from '../../../utils/errorHandler'
|
|
|
+import { AuthContext } from '../../../types/context'
|
|
|
+
|
|
|
+const SimpleRegisterSchema = z.object({
|
|
|
+ username: z.string().min(3).openapi({
|
|
|
+ example: 'john_doe',
|
|
|
+ description: '用户名'
|
|
|
+ })
|
|
|
+})
|
|
|
+
|
|
|
+const TokenResponseSchema = z.object({
|
|
|
+ token: z.string().openapi({
|
|
|
+ example: 'jwt.token.here',
|
|
|
+ description: 'JWT Token'
|
|
|
+ }),
|
|
|
+ user: z.object({
|
|
|
+ id: z.number(),
|
|
|
+ username: z.string()
|
|
|
+ })
|
|
|
+})
|
|
|
+
|
|
|
+const userService = new UserService(AppDataSource)
|
|
|
+const authService = new AuthService(userService)
|
|
|
+
|
|
|
+const simpleRegisterRoute = createRoute({
|
|
|
+ method: 'post',
|
|
|
+ path: '/register/simple',
|
|
|
+ request: {
|
|
|
+ body: {
|
|
|
+ content: {
|
|
|
+ 'application/json': {
|
|
|
+ schema: SimpleRegisterSchema
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ },
|
|
|
+ responses: {
|
|
|
+ 201: {
|
|
|
+ description: '注册成功',
|
|
|
+ content: {
|
|
|
+ 'application/json': {
|
|
|
+ schema: TokenResponseSchema
|
|
|
+ }
|
|
|
+ }
|
|
|
+ },
|
|
|
+ 400: {
|
|
|
+ description: '请求参数错误',
|
|
|
+ content: {
|
|
|
+ 'application/json': {
|
|
|
+ schema: ErrorSchema
|
|
|
+ }
|
|
|
+ }
|
|
|
+ },
|
|
|
+ 500: {
|
|
|
+ description: '服务器错误',
|
|
|
+ content: {
|
|
|
+ 'application/json': {
|
|
|
+ schema: ErrorSchema
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+})
|
|
|
+
|
|
|
+const app = new OpenAPIHono<AuthContext>().openapi(simpleRegisterRoute, async (c) => {
|
|
|
+ try {
|
|
|
+ const { username } = c.req.valid('json')
|
|
|
+
|
|
|
+ // 生成唯一的用户名
|
|
|
+ const uniqueUsername = await userService.generateUniqueUsername(username)
|
|
|
+
|
|
|
+ // 使用默认密码
|
|
|
+ const defaultPassword = '123456'
|
|
|
+
|
|
|
+ // 创建用户
|
|
|
+ const user = await userService.createUser({
|
|
|
+ username: uniqueUsername,
|
|
|
+ password: defaultPassword
|
|
|
+ })
|
|
|
+
|
|
|
+ const token = authService.generateToken(user)
|
|
|
+ return c.json({ token, user: { id: user.id, username: user.username } }, 201)
|
|
|
+ } catch (error) {
|
|
|
+ console.error('简单注册失败:', error)
|
|
|
+ const message = error instanceof Error ? error.message : '注册失败'
|
|
|
+ return c.json({ code: 500, message }, 500)
|
|
|
+ }
|
|
|
+})
|
|
|
+
|
|
|
+export default app
|