2
0
Просмотр исходного кода

✨ feat(auth): 添加简易注册功能

- 新增简易注册接口 `/register/simple`,仅需提供用户名
- 实现用户名自动去重机制,重复时添加4位随机数字后缀
- 在auth路由中注册简易注册接口路由

✨ feat(user): 添加用户名生成服务

- 实现`generateUniqueUsername`方法,支持生成唯一用户名
- 添加最大尝试次数限制,默认10次
- 随机后缀采用4位数字格式,范围1000-9999
yourname 6 месяцев назад
Родитель
Сommit
b8c9e614fd

+ 2 - 0
src/server/api/auth/index.ts

@@ -3,6 +3,7 @@ import loginRoute from './login/password';
 import logoutRoute from './logout';
 import meRoute from './me/get';
 import registerRoute from './register/create';
+import simpleRegisterRoute from './register/simple';
 import ssoVerify from './sso-verify';
 
 const app = new OpenAPIHono()
@@ -10,6 +11,7 @@ const app = new OpenAPIHono()
   .route('/', logoutRoute)
   .route('/', meRoute)
   .route('/', registerRoute)
+  .route('/', simpleRegisterRoute)
   .route('/', ssoVerify);
 
 export default app;

+ 95 - 0
src/server/api/auth/register/simple.ts

@@ -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

+ 26 - 0
src/server/modules/users/user.service.ts

@@ -164,4 +164,30 @@ export class UserService {
       throw new Error('Failed to get user by account');
     }
   }
+
+  /**
+   * 生成唯一的用户名,如果用户名已存在则添加随机数字
+   * @param username 基础用户名
+   * @param maxAttempts 最大尝试次数,默认10次
+   * @returns 唯一的用户名
+   */
+  async generateUniqueUsername(username: string, maxAttempts: number = 10): Promise<string> {
+    let uniqueUsername = username;
+    let attempt = 0;
+    
+    while (attempt < maxAttempts) {
+      const existingUser = await this.getUserByUsername(uniqueUsername);
+      
+      if (!existingUser) {
+        return uniqueUsername;
+      }
+      
+      // 生成4位随机数字
+      const randomSuffix = Math.floor(1000 + Math.random() * 9000);
+      uniqueUsername = `${username}${randomSuffix}`;
+      attempt++;
+    }
+    
+    throw new Error(`无法生成唯一的用户名,请尝试其他用户名`);
+  }
 }