sso-verify.route.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. const routeDef = createRoute({
  7. method: 'get',
  8. path: '/sso-verify',
  9. responses: {
  10. 200: {
  11. description: 'SSO验证成功',
  12. headers: {
  13. 'X-Username': {
  14. schema: { type: 'string' },
  15. description: '格式化后的用户名'
  16. }
  17. }
  18. },
  19. 401: {
  20. description: '未授权或令牌无效',
  21. content: {
  22. 'application/json': {
  23. schema: ErrorSchema
  24. }
  25. }
  26. },
  27. 500: {
  28. description: '服务器错误',
  29. content: {
  30. 'application/json': {
  31. schema: ErrorSchema
  32. }
  33. }
  34. }
  35. }
  36. });
  37. const app = new OpenAPIHono().openapi(routeDef, async (c) => {
  38. try {
  39. // 在路由处理函数内部初始化服务
  40. const userService = new UserService(AppDataSource);
  41. const authService = new AuthService(userService);
  42. const token = c.req.header('Authorization')?.replace('Bearer ', '');
  43. if (!token) {
  44. return c.json({ code: 401, message: '未提供授权令牌' }, 401);
  45. }
  46. try {
  47. const userData = await authService.verifyToken(token);
  48. if (!userData) {
  49. return c.json({ code: 401, message: '无效令牌' }, 401);
  50. }
  51. return c.text('OK', 200);
  52. } catch (tokenError) {
  53. return c.json({ code: 401, message: '令牌验证失败' }, 401);
  54. }
  55. } catch (error) {
  56. return c.json({ code: 500, message: 'SSO验证失败' }, 500);
  57. }
  58. });
  59. export default app;