middlewares.ts 3.0 KB

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