sso-verify.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi'
  2. import { AuthService } from '@/server/modules/auth/auth.service'
  3. import { UserService } from '@/server/modules/users/user.service'
  4. import { ErrorSchema } from '@/server/utils/errorHandler'
  5. import { AppDataSource } from '@/server/data-source'
  6. import { AuthContext } from '@/server/types/context'
  7. const userService = new UserService(AppDataSource)
  8. const authService = new AuthService(userService)
  9. const routeDef = createRoute({
  10. method: 'get',
  11. path: '/sso-verify',
  12. responses: {
  13. 200: {
  14. description: 'SSO验证成功',
  15. headers: {
  16. 'X-Username': {
  17. schema: { type: 'string' },
  18. description: '格式化后的用户名'
  19. }
  20. }
  21. },
  22. 401: {
  23. description: '未授权或令牌无效',
  24. content: {
  25. 'application/json': {
  26. schema: ErrorSchema
  27. }
  28. }
  29. },
  30. 500: {
  31. description: '服务器错误',
  32. content: {
  33. 'application/json': {
  34. schema: ErrorSchema
  35. }
  36. }
  37. }
  38. }
  39. })
  40. const app = new OpenAPIHono().openapi(routeDef, async (c) => {
  41. try {
  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