112 lines
3.0 KiB
TypeScript
112 lines
3.0 KiB
TypeScript
import { Hono } from 'hono'
|
|
import { cors } from 'hono/cors'
|
|
import type { Context as HonoContext } from 'hono'
|
|
import { Auth } from '@d8d-appcontainer/auth'
|
|
import type { User as AuthUser } from '@d8d-appcontainer/auth'
|
|
import { APIClient } from '@d8d-appcontainer/api'
|
|
import type { SystemSettingRecord } from '../client/share/types.ts'
|
|
import debug from "debug"
|
|
|
|
const log = {
|
|
auth: debug('auth:server')
|
|
}
|
|
|
|
// 定义自定义上下文类型
|
|
export interface Variables {
|
|
auth: Auth
|
|
user?: AuthUser
|
|
apiClient: APIClient
|
|
moduleDir: string
|
|
systemSettings?: SystemSettingRecord
|
|
}
|
|
// 认证中间件
|
|
export const withAuth = async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
|
|
try {
|
|
const auth = c.get('auth')
|
|
|
|
const token = c.req.header('Authorization')?.replace('Bearer ', '')
|
|
if (token) {
|
|
const userData = await auth.verifyToken(token)
|
|
if (userData) {
|
|
c.set('user', userData)
|
|
await next()
|
|
return
|
|
}
|
|
}
|
|
|
|
return c.json({ error: '未授权' }, 401)
|
|
} catch (error) {
|
|
log.auth('认证失败:', error)
|
|
return c.json({ error: '无效凭证' }, 401)
|
|
}
|
|
}
|
|
|
|
// 导出withAuth类型定义
|
|
export type WithAuth = typeof withAuth;
|
|
|
|
// 环境变量设置中间件
|
|
export const setEnvVariables = (apiClient: APIClient, moduleDir: string) => {
|
|
return async (c: HonoContext<{ Variables: Variables }>, next: () => Promise<void>) => {
|
|
c.set('apiClient', apiClient)
|
|
c.set('moduleDir', moduleDir)
|
|
c.set('auth', await initAuth(apiClient))
|
|
c.set('systemSettings', await initSystemSettings(apiClient))
|
|
await next()
|
|
}
|
|
}
|
|
|
|
// CORS中间件
|
|
export const corsMiddleware = cors()
|
|
|
|
// 初始化Auth实例
|
|
const initAuth = async (apiClient: APIClient) => {
|
|
try {
|
|
log.auth('正在初始化Auth实例')
|
|
|
|
const auth = new Auth(apiClient as any, {
|
|
jwtSecret: Deno.env.get("JWT_SECRET") || 'your-jwt-secret-key',
|
|
initialUsers: [],
|
|
storagePrefix: '',
|
|
userTable: 'users',
|
|
fieldNames: {
|
|
id: 'id',
|
|
username: 'username',
|
|
password: 'password',
|
|
phone: 'phone',
|
|
email: 'email',
|
|
is_disabled: 'is_disabled',
|
|
is_deleted: 'is_deleted'
|
|
},
|
|
tokenExpiry: 24 * 60 * 60,
|
|
refreshTokenExpiry: 7 * 24 * 60 * 60
|
|
})
|
|
|
|
log.auth('Auth实例初始化完成')
|
|
return auth
|
|
|
|
} catch (error) {
|
|
log.auth('Auth初始化失败:', error)
|
|
throw error
|
|
}
|
|
}
|
|
|
|
// 初始化系统设置
|
|
const initSystemSettings = async (apiClient: APIClient) => {
|
|
try {
|
|
const systemSettings = await apiClient.database.table('system_settings')
|
|
.select()
|
|
|
|
// 将系统设置转换为键值对形式
|
|
const settings = systemSettings.reduce((acc: Record<string, any>, setting: any) => {
|
|
acc[setting.key] = setting.value
|
|
return acc
|
|
}, {}) as SystemSettingRecord
|
|
|
|
return settings
|
|
|
|
} catch (error) {
|
|
log.auth('获取系统设置失败:', error)
|
|
return {} as SystemSettingRecord
|
|
}
|
|
}
|