middlewares.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { Hono } from 'hono'
  2. import { cors } from 'hono/cors'
  3. import type { Context as HonoContext } from 'hono'
  4. import { Auth } from '@d8d-appcontainer/auth'
  5. import type { User as AuthUser } from '@d8d-appcontainer/auth'
  6. import { APIClient } from '@d8d-appcontainer/api'
  7. import type { SystemSettingRecord } from '../client/share/types.ts'
  8. import debug from "debug"
  9. const log = {
  10. auth: debug('auth:server')
  11. }
  12. // 定义自定义上下文类型
  13. export interface Variables {
  14. auth: Auth
  15. user?: AuthUser
  16. apiClient: APIClient
  17. moduleDir: string
  18. systemSettings?: SystemSettingRecord
  19. }
  20. export type VariablesContext = HonoContext<{ Variables: Variables }>;
  21. // 认证中间件
  22. export const withAuth = async (c: VariablesContext, next: () => Promise<void>) => {
  23. try {
  24. const auth = c.get('auth')
  25. const token = c.req.header('Authorization')?.replace('Bearer ', '')
  26. if (token) {
  27. const userData = await auth.verifyToken(token)
  28. if (userData) {
  29. c.set('user', userData)
  30. await next()
  31. return
  32. }
  33. }
  34. return c.json({ error: '未授权' }, 401)
  35. } catch (error) {
  36. log.auth('认证失败:', error)
  37. return c.json({ error: '无效凭证' }, 401)
  38. }
  39. }
  40. // 导出withAuth类型定义
  41. export type WithAuth = typeof withAuth;
  42. // 环境变量设置中间件
  43. export const setEnvVariables = (apiClient: APIClient, moduleDir: string) => {
  44. return async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
  45. c.set('apiClient', apiClient)
  46. c.set('moduleDir', moduleDir)
  47. c.set('auth', await initAuth(apiClient))
  48. c.set('systemSettings', await initSystemSettings(apiClient))
  49. await next()
  50. }
  51. }
  52. // CORS中间件
  53. export const corsMiddleware = cors()
  54. // 初始化Auth实例
  55. const initAuth = async (apiClient: APIClient) => {
  56. try {
  57. log.auth('正在初始化Auth实例')
  58. const auth = new Auth(apiClient as any, {
  59. jwtSecret: Deno.env.get("JWT_SECRET") || 'your-jwt-secret-key',
  60. initialUsers: [],
  61. storagePrefix: '',
  62. userTable: 'users',
  63. fieldNames: {
  64. id: 'id',
  65. username: 'username',
  66. password: 'password',
  67. phone: 'phone',
  68. email: 'email',
  69. is_disabled: 'is_disabled',
  70. is_deleted: 'is_deleted'
  71. },
  72. tokenExpiry: 24 * 60 * 60,
  73. refreshTokenExpiry: 7 * 24 * 60 * 60
  74. })
  75. log.auth('Auth实例初始化完成')
  76. return auth
  77. } catch (error) {
  78. log.auth('Auth初始化失败:', error)
  79. throw error
  80. }
  81. }
  82. // 初始化系统设置
  83. const initSystemSettings = async (apiClient: APIClient) => {
  84. try {
  85. const systemSettings = await apiClient.database.table('system_settings')
  86. .select()
  87. // 将系统设置转换为键值对形式
  88. const settings = systemSettings.reduce((acc: Record<string, any>, setting: any) => {
  89. acc[setting.key] = setting.value
  90. return acc
  91. }, {}) as SystemSettingRecord
  92. return settings
  93. } catch (error) {
  94. log.auth('获取系统设置失败:', error)
  95. return {} as SystemSettingRecord
  96. }
  97. }