sso-verify.ts 1.6 KB

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