login.route.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { AuthService } from '../services';
  3. import { UserService } from '@d8d/user-module';
  4. import { ErrorSchema } from '@d8d/shared-utils';
  5. import { AppDataSource } from '@d8d/shared-utils';
  6. import { AuthContext } from '@d8d/shared-types';
  7. import { parseWithAwait } from '@d8d/shared-utils';
  8. import { LoginSchema, TokenResponseSchema } from '../schemas';
  9. const loginRoute = createRoute({
  10. method: 'post',
  11. path: '/login',
  12. request: {
  13. body: {
  14. content: {
  15. 'application/json': {
  16. schema: LoginSchema
  17. }
  18. }
  19. }
  20. },
  21. responses: {
  22. 200: {
  23. description: '登录成功',
  24. content: {
  25. 'application/json': {
  26. schema: TokenResponseSchema
  27. }
  28. }
  29. },
  30. 401: {
  31. description: '用户名或密码错误',
  32. content: {
  33. 'application/json': {
  34. schema: ErrorSchema
  35. }
  36. }
  37. },
  38. 500: {
  39. description: '服务器内部错误',
  40. content: {
  41. 'application/json': {
  42. schema: ErrorSchema
  43. }
  44. }
  45. }
  46. }
  47. });
  48. const app = new OpenAPIHono<AuthContext>().openapi(loginRoute, async (c) => {
  49. try {
  50. // 在路由处理函数内部初始化服务
  51. const userService = new UserService(AppDataSource);
  52. const authService = new AuthService(userService);
  53. const { username, password } = c.req.valid('json');
  54. const result = await authService.login(username, password);
  55. return c.json(await parseWithAwait(TokenResponseSchema, result), 200);
  56. } catch (error) {
  57. // 认证相关错误返回401
  58. if (error instanceof Error &&
  59. (error.message.includes('User not found') ||
  60. error.message.includes('Invalid password') ||
  61. error.message.includes('User account is disabled'))) {
  62. return c.json(
  63. {
  64. code: 401,
  65. message: error.message.includes('User account is disabled') ? '账户已禁用' : '用户名或密码错误'
  66. },
  67. 401
  68. );
  69. }
  70. // 其他错误重新抛出,由错误处理中间件处理
  71. throw error;
  72. }
  73. });
  74. export default app;