import { createRoute, OpenAPIHono } from '@hono/zod-openapi'; import { AuthService } from '../services'; import { UserService } from '@d8d/user-module-mt'; import { ErrorSchema } from '@d8d/shared-utils'; import { AppDataSource } from '@d8d/shared-utils'; import { AuthContext } from '@d8d/shared-types'; import { parseWithAwait } from '@d8d/shared-utils'; import { LoginSchema, TokenResponseSchema } from '../schemas'; const loginRoute = createRoute({ method: 'post', path: '/login', request: { body: { content: { 'application/json': { schema: LoginSchema } } } }, responses: { 200: { description: '登录成功', content: { 'application/json': { schema: TokenResponseSchema } } }, 401: { description: '用户名或密码错误', content: { 'application/json': { schema: ErrorSchema } } }, 500: { description: '服务器内部错误', content: { 'application/json': { schema: ErrorSchema } } } } }); const app = new OpenAPIHono().openapi(loginRoute, async (c) => { try { // 在路由处理函数内部初始化服务 const userService = new UserService(AppDataSource); const authService = new AuthService(userService); const { username, password } = c.req.valid('json'); // 从请求头或查询参数中提取租户ID const tenantId = c.req.header('X-Tenant-Id') || c.req.query('tenantId'); const tenantIdNumber = tenantId ? parseInt(tenantId, 10) : undefined; const result = await authService.login(username, password, tenantIdNumber); return c.json(await parseWithAwait(TokenResponseSchema, result), 200); } catch (error) { // 认证相关错误返回401 if (error instanceof Error && (error.message.includes('User not found') || error.message.includes('Invalid password') || error.message.includes('User account is disabled') || error.message.includes('User does not belong to this tenant'))) { return c.json( { code: 401, message: error.message.includes('User account is disabled') ? '账户已禁用' : error.message.includes('User does not belong to this tenant') ? '用户不属于该租户' : '用户名或密码错误' }, 401 ); } // 其他错误重新抛出,由错误处理中间件处理 throw error; } }); export default app;