login.route.ts 2.2 KB

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