logout.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { z } from '@hono/zod-openapi'
  3. import { AuthContext } from '@/server/types/context';
  4. import { authMiddleware } from '@/server/middleware/auth.middleware';
  5. import { AppDataSource } from '@/server/data-source';
  6. import { AuthService } from '@/server/modules/auth/auth.service';
  7. import { UserService } from '@/server/modules/users/user.service';
  8. import { ErrorSchema } from '@/server/utils/errorHandler';
  9. // 初始化服务
  10. const userService = new UserService(AppDataSource);
  11. const authService = new AuthService(userService);
  12. const SuccessSchema = z.object({
  13. message: z.string().openapi({ example: '登出成功' })
  14. })
  15. // 定义路由
  16. const routeDef = createRoute({
  17. method: 'post',
  18. path: '/logout',
  19. security: [{ Bearer: [] }],
  20. middleware: [authMiddleware],
  21. responses: {
  22. 200: {
  23. description: '登出成功',
  24. content: {
  25. 'application/json': {
  26. schema: SuccessSchema
  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(routeDef, async (c) => {
  49. try {
  50. const token = c.get('token');
  51. const decoded = authService.verifyToken(token);
  52. if (!decoded) {
  53. return c.json({ code: 401, message: '未授权' }, 401);
  54. }
  55. await authService.logout(token);
  56. return c.json({ message: '登出成功' }, 200);
  57. } catch (error) {
  58. console.error('登出失败:', error);
  59. return c.json({ code: 500, message: '登出失败' }, 500);
  60. }
  61. });
  62. export default app;