From 541e24c6f42ee091a798e64323cd04b888f196bc Mon Sep 17 00:00:00 2001 From: chenchun Date: Sun, 9 Aug 2026 02:01:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=90=8E=E5=8F=B0=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E5=91=98=E7=8B=AC=E7=AB=8B=E8=B4=A6=E5=8F=B7=E4=BD=93=E7=B3=BB?= =?UTF-8?q?=EF=BC=8CCasdoor=20=E9=85=8D=E7=BD=AE=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E5=90=8E=E5=8F=B0=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 admin_users/admin_sessions 表与 adminAuth 工具(scrypt 密码 + 独立会话 Cookie) - /admin/init 初始化首个管理员,未初始化时服务端/客户端双守卫引导 - 后台鉴权改为管理员会话,前台 Casdoor 用户一律普通用户、与后台解耦 - Casdoor 配置改存 settings 表并由「统一认证」页管理,移除全部 CASDOOR 环境变量 - 侧边栏增加统一认证/管理员入口与登出;LoginModal 感知 SSO 启用状态 - 补充 adminAuth 测试,重写 casdoor 测试,全部 23 项通过 --- .env.example | 21 -- app/components/admin/AdminSidebar.vue | 33 ++- app/components/common/LoginModal.vue | 58 ++-- app/layouts/login.vue | 12 + app/middleware/admin.ts | 25 +- app/middleware/init.global.ts | 24 ++ app/pages/account.vue | 19 +- app/pages/admin/admins.vue | 287 ++++++++++++++++++++ app/pages/admin/casdoor.vue | 127 +++++++++ app/pages/admin/init.vue | 75 +++++ app/pages/admin/login.vue | 61 +++++ app/plugins/admin-auth.client.ts | 11 + app/stores/admin.ts | 70 +++++ app/utils/casdoorClient.ts | 63 +++-- deploy.sh | 15 - i18n/locales/en.json | 1 + i18n/locales/zh.json | 1 + nuxt.config.ts | 16 +- server/api/admin/admin-users.get.ts | 13 + server/api/admin/admin-users.post.ts | 34 +++ server/api/admin/admin-users/[id].delete.ts | 27 ++ server/api/admin/admin-users/[id].patch.ts | 52 ++++ server/api/admin/casdoor-config.get.ts | 11 + server/api/admin/casdoor-config.patch.ts | 27 ++ server/api/auth/admin-init-status.get.ts | 8 + server/api/auth/admin-init.post.ts | 39 +++ server/api/auth/admin/login.post.ts | 25 ++ server/api/auth/admin/logout.post.ts | 14 + server/api/auth/admin/me.get.ts | 13 + server/api/auth/callback.get.ts | 2 +- server/api/auth/casdoor-config.get.ts | 9 + server/api/auth/casdoor-login.get.ts | 2 +- server/middleware/init-guard.ts | 15 + server/utils/adminAuth.ts | 117 ++++++++ server/utils/audit.ts | 8 +- server/utils/auth.ts | 25 +- server/utils/casdoor.ts | 67 ++--- server/utils/casdoorConfig.ts | 133 +++++++++ server/utils/config.ts | 60 ---- server/utils/db.ts | 19 ++ tests/adminAuth.test.ts | 50 ++++ tests/casdoor.test.ts | 123 +++++---- 42 files changed, 1505 insertions(+), 307 deletions(-) create mode 100644 app/layouts/login.vue create mode 100644 app/middleware/init.global.ts create mode 100644 app/pages/admin/admins.vue create mode 100644 app/pages/admin/casdoor.vue create mode 100644 app/pages/admin/init.vue create mode 100644 app/pages/admin/login.vue create mode 100644 app/plugins/admin-auth.client.ts create mode 100644 app/stores/admin.ts create mode 100644 server/api/admin/admin-users.get.ts create mode 100644 server/api/admin/admin-users.post.ts create mode 100644 server/api/admin/admin-users/[id].delete.ts create mode 100644 server/api/admin/admin-users/[id].patch.ts create mode 100644 server/api/admin/casdoor-config.get.ts create mode 100644 server/api/admin/casdoor-config.patch.ts create mode 100644 server/api/auth/admin-init-status.get.ts create mode 100644 server/api/auth/admin-init.post.ts create mode 100644 server/api/auth/admin/login.post.ts create mode 100644 server/api/auth/admin/logout.post.ts create mode 100644 server/api/auth/admin/me.get.ts create mode 100644 server/api/auth/casdoor-config.get.ts create mode 100644 server/middleware/init-guard.ts create mode 100644 server/utils/adminAuth.ts create mode 100644 server/utils/casdoorConfig.ts create mode 100644 tests/adminAuth.test.ts diff --git a/.env.example b/.env.example index 216b0c1..80434d0 100644 --- a/.env.example +++ b/.env.example @@ -25,27 +25,6 @@ NUXT_SMTP_FROM= # 联系表单留言的接收邮箱 NUXT_CONTACT_TO=chenchun@virtheart.com -# ---- Casdoor 统一身份认证(SSO)---- -# 登录/注册全部在 Casdoor 侧完成;本站仅记录用户身份并维护本地会话 -NUXT_CASDOOR_SERVER_URL=https://sys.virtheart.com -NUXT_CASDOOR_CLIENT_ID=a0ba9570e0bcfbeb9f67 -NUXT_CASDOOR_CLIENT_SECRET= -NUXT_CASDOOR_ORG_NAME=virtheart -NUXT_CASDOOR_APP_NAME=virtheat-personal -# 应用证书公钥 PEM:Casdoor「应用 -> Certificates」页复制,可 base64 或原文写入 -# base64: cat cert.pem | base64 | tr -d '\n' -NUXT_CASDOOR_CERT_B64= -# 命中任一角色名即管理员(对应 Casdoor 用户角色;token 的 IsAdmin 字段同样生效) -NUXT_CASDOOR_ADMIN_ROLES=admin -# 回调用路径(redirect_uri = NUXT_PUBLIC_SITE_URL + 该路径,需与 Casdoor 应用配置一致) -NUXT_CASDOOR_CALLBACK_PATH=/api/auth/callback -# 浏览器端可见的 Casdoor 配置(不含任何 secret;用于注册页/登出地址等) -NUXT_PUBLIC_CASDOOR_SERVER_URL=https://sys.virtheart.com -NUXT_PUBLIC_CASDOOR_CLIENT_ID=a0ba9570e0bcfbeb9f67 -NUXT_PUBLIC_CASDOOR_ORG_NAME=virtheart -NUXT_PUBLIC_CASDOOR_APP_NAME=virtheat-personal -NUXT_PUBLIC_CASDOOR_REDIRECT_PATH=/api/auth/callback - # ---- OSS 文件存储(RustFS / S3 v4 兼容;凭据不写入仓库,生产由 deploy.sh 注入 Secret)---- NUXT_OSS_ENDPOINT=oss.virtheart.com NUXT_OSS_ACCESS_KEY= diff --git a/app/components/admin/AdminSidebar.vue b/app/components/admin/AdminSidebar.vue index 5af8112..589817d 100644 --- a/app/components/admin/AdminSidebar.vue +++ b/app/components/admin/AdminSidebar.vue @@ -1,14 +1,22 @@ + + \ No newline at end of file diff --git a/app/middleware/admin.ts b/app/middleware/admin.ts index db48bae..0e99416 100644 --- a/app/middleware/admin.ts +++ b/app/middleware/admin.ts @@ -1,23 +1,22 @@ import { defineNuxtRouteMiddleware, navigateTo } from '#app' -import { useUserStore } from '~/stores/user' -import { useAuthModalStore } from '~/stores/authModal' +import { useAdminStore } from '~/stores/admin' /** - * 后台路由守卫(/admin/**):仅管理员可访问。 - * - SSR 不拦截(真实防护在 admin API 的 requireAdmin); - * - 客户端依据已恢复的会话判定,未登录则弹出登录框并回退,非管理员回首页。 + * 后台路由守卫(/admin/**):仅后台管理员可访问。 + * - SSR 不拦截(真实防护在后台 API 的 requireAdmin); + * - 客户端依据已恢复的管理员会话判定,未登录跳登录页,未初始化跳初始化页。 */ export default defineNuxtRouteMiddleware(() => { if (import.meta.server) return - const userStore = useUserStore() + const adminStore = useAdminStore() - if (!userStore.isAuthenticated) { - const authModal = useAuthModalStore() - authModal.openLogin() - return navigateTo('/account') + // 系统尚未初始化首个管理员 → 引导初始化 + if (adminStore.needsInit === true) { + return navigateTo('/admin/init') } - if (userStore.user?.role !== 'admin') { - return navigateTo('/') + + if (!adminStore.isAuthenticated) { + return navigateTo('/admin/login') } -}) +}) \ No newline at end of file diff --git a/app/middleware/init.global.ts b/app/middleware/init.global.ts new file mode 100644 index 0000000..2da1795 --- /dev/null +++ b/app/middleware/init.global.ts @@ -0,0 +1,24 @@ +import { defineNuxtRouteMiddleware, navigateTo } from '#app' + +/** + * 首个管理员初始化引导(客户端)。 + * - 系统未初始化 → 访问任意 /admin 页面强制跳 /admin/init + * - 已初始化 → 不能停留在 /admin/init(已登录管理员跳后台,否则跳登录页) + */ +export default defineNuxtRouteMiddleware((to) => { + if (import.meta.server) return + + const adminStore = useAdminStore() + const initialized = adminStore.needsInit === false + + if (to.path === '/admin/init') { + if (initialized) { + return navigateTo(adminStore.isAuthenticated ? '/admin' : '/admin/login') + } + return + } + + if (adminStore.needsInit === true && to.path.startsWith('/admin/')) { + return navigateTo('/admin/init') + } +}) \ No newline at end of file diff --git a/app/pages/account.vue b/app/pages/account.vue index ffcb320..a97930f 100644 --- a/app/pages/account.vue +++ b/app/pages/account.vue @@ -21,8 +21,6 @@ const apiError = useApiError() useSeoMeta({ title: () => t('account.title') }) -const isAdmin = computed(() => userStore.user?.role === 'admin') - const formatDate = (raw?: string, monthOnly = false) => { if (!raw) return '' const d = new Date(String(raw).replace(' ', 'T') + 'Z') @@ -157,12 +155,9 @@ onBeforeUnmount(() => ctx?.revert())

{{ userStore.user?.username }}

- - - {{ isAdmin ? t('account.roleAdmin') : t('account.roleUser') }} + + + {{ t('account.roleUser') }}

{{ userStore.user?.email }}

@@ -170,14 +165,6 @@ onBeforeUnmount(() => ctx?.revert()) {{ t('account.joinedAt') }} · {{ formatDate(userStore.user?.createdAt) }}

- - {{ t('account.adminEntry') }} - - diff --git a/app/pages/admin/admins.vue b/app/pages/admin/admins.vue new file mode 100644 index 0000000..24f0fba --- /dev/null +++ b/app/pages/admin/admins.vue @@ -0,0 +1,287 @@ + + + \ No newline at end of file diff --git a/app/pages/admin/casdoor.vue b/app/pages/admin/casdoor.vue new file mode 100644 index 0000000..abd25ef --- /dev/null +++ b/app/pages/admin/casdoor.vue @@ -0,0 +1,127 @@ + + + \ No newline at end of file diff --git a/app/pages/admin/init.vue b/app/pages/admin/init.vue new file mode 100644 index 0000000..00f8ba3 --- /dev/null +++ b/app/pages/admin/init.vue @@ -0,0 +1,75 @@ + + + \ No newline at end of file diff --git a/app/pages/admin/login.vue b/app/pages/admin/login.vue new file mode 100644 index 0000000..50d73b2 --- /dev/null +++ b/app/pages/admin/login.vue @@ -0,0 +1,61 @@ + + + \ No newline at end of file diff --git a/app/plugins/admin-auth.client.ts b/app/plugins/admin-auth.client.ts new file mode 100644 index 0000000..9ddcf7e --- /dev/null +++ b/app/plugins/admin-auth.client.ts @@ -0,0 +1,11 @@ +import { defineNuxtPlugin } from '#app' + +/** + * 客户端启动时恢复后台管理员会话,并检查系统是否已初始化首个管理员。 + * 在路由守卫之前完成,保证 admin 中间件与 /admin/init 守卫能拿到真实状态。 + */ +export default defineNuxtPlugin(async () => { + const adminStore = useAdminStore() + await adminStore.restoreAdmin() + await adminStore.checkInit() +}) \ No newline at end of file diff --git a/app/stores/admin.ts b/app/stores/admin.ts new file mode 100644 index 0000000..24b7280 --- /dev/null +++ b/app/stores/admin.ts @@ -0,0 +1,70 @@ +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' + +export interface Admin { + id: number + username: string + createdAt: string +} + +export interface ApiResult { + success: boolean + /** 后端错误码(供 useApiError 翻译),成功时为 null */ + code?: string | null +} + +/** + * 后台管理员会话(独立于 Casdoor 前台用户体系,凭 admin_users 表 + 独立 Cookie)。 + * - restoreAdmin:从服务端会话恢复当前管理员(启动时由插件调用) + * - checkInit:系统是否已创建首个管理员(未创建时客户端强制引导到 /admin/init) + * - login / logout:管理员登录页与侧边栏登出 + */ +export const useAdminStore = defineStore('admin', () => { + const admin = ref(null) + const isAuthenticated = computed(() => admin.value !== null) + + // 系统是否尚未初始化首个管理员(null = 未知,加载中) + const needsInit = ref(null) + + const restoreAdmin = async (): Promise => { + try { + const data = await $fetch<{ admin: Admin }>('/api/auth/admin/me') + admin.value = data.admin + } catch { + admin.value = null + } + } + + const checkInit = async (): Promise => { + try { + const data = await $fetch<{ needsInit: boolean }>('/api/auth/admin-init-status') + needsInit.value = data.needsInit + } catch { + needsInit.value = false + } + } + + const login = async (username: string, password: string): Promise => { + try { + const data = await $fetch<{ admin: Admin }>('/api/auth/admin/login', { + method: 'POST', + body: { username, password }, + }) + admin.value = data.admin + return { success: true } + } catch (err) { + return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' } + } + } + + const logout = async (): Promise => { + try { + await $fetch('/api/auth/admin/logout', { method: 'POST' }) + } catch (err) { + console.error('admin logout error:', err) + } + admin.value = null + } + + return { admin, isAuthenticated, needsInit, restoreAdmin, checkInit, login, logout } +}) \ No newline at end of file diff --git a/app/utils/casdoorClient.ts b/app/utils/casdoorClient.ts index 886bb78..30c9740 100644 --- a/app/utils/casdoorClient.ts +++ b/app/utils/casdoorClient.ts @@ -1,48 +1,53 @@ -import { useRuntimeConfig } from '#app' +import { ref } from 'vue' /** - * Casdoor 客户端配置读取(public runtimeConfig 注入,不含任何 secret)。 - * 登录跳转走后端端点 /api/auth/casdoor-login,这里仅提供注册页与单点登出地址。 + * Casdoor 客户端公共配置读取(来自后端 /api/auth/casdoor-config,不含任何 secret)。 + * 配置由后台「统一认证」页管理,故客户端在组件挂载时拉取最新值。 + * 登录跳转走后端端点 /api/auth/casdoor-login,这里仅提供启用状态、注册页与单点登出地址。 */ export interface CasdoorPublic { + enabled: boolean serverUrl: string clientId: string orgName: string appName: string - redirectPath: string + callbackPath: string + redirectUri: string } -export function getCasdoorPublic(): CasdoorPublic { - const c = useRuntimeConfig() - const pub = (c.public ?? {}) as Record - return { - serverUrl: (pub.casdoorServerUrl as string) || '', - clientId: (pub.casdoorClientId as string) || '', - orgName: (pub.casdoorOrgName as string) || '', - appName: (pub.casdoorAppName as string) || '', - redirectPath: (pub.casdoorRedirectPath as string) || '/api/auth/callback', +export interface CasdoorClientState { + config: CasdoorPublic | null + loaded: boolean + /** 拉取公开配置(成功或失败都置 loaded=true) */ + load: () => Promise +} + +export function useCasdoorPublic(): CasdoorClientState { + const config = ref(null) + const loaded = ref(false) + + const load = async () => { + try { + config.value = await $fetch('/api/auth/casdoor-config') + } catch { + config.value = null + } finally { + loaded.value = true + } } + + return { config, loaded, load } } /** 注册账号统一在 Casdoor 完成 */ -export function getCasdoorSignupUrl(): string { - const { serverUrl, appName } = getCasdoorPublic() - if (!serverUrl || !appName) return '' - return `${serverUrl}/signup/${appName}` -} - -/** 本站回调完整地址(用于登出回跳) */ -export function getCasdoorRedirectUri(): string { - const { redirectPath } = getCasdoorPublic() - const { public: p } = useRuntimeConfig() - const siteUrl = String((p as any).siteUrl || '').replace(/\/$/, '') - return `${siteUrl}${redirectPath}` +export function getCasdoorSignupUrl(cfg: CasdoorPublic): string { + if (!cfg.serverUrl || !cfg.appName) return '' + return `${cfg.serverUrl}/signup/${cfg.appName}` } /** 单点登出地址(可选使用:登出后跳回本站回调) */ -export function getCasdoorLogoutUrl(): string { - const { serverUrl, clientId } = getCasdoorPublic() - if (!serverUrl || !clientId) return '' - return `${serverUrl}/logout?client_id=${clientId}&redirect_uri=${encodeURIComponent(getCasdoorRedirectUri())}` +export function getCasdoorLogoutUrl(cfg: CasdoorPublic): string { + if (!cfg.serverUrl || !cfg.clientId) return '' + return `${cfg.serverUrl}/logout?client_id=${cfg.clientId}&redirect_uri=${encodeURIComponent(cfg.redirectUri)}` } \ No newline at end of file diff --git a/deploy.sh b/deploy.sh index 8380968..8c74760 100755 --- a/deploy.sh +++ b/deploy.sh @@ -16,7 +16,6 @@ # SESSION_SECRET 会话密钥(缺省复用已有或自动生成) # SMTP_HOST/PORT/USER/PASS/FROM 邮件 # CONTACT_TO 联系表单收件邮箱 -# CASDOOR_CLIENT_ID/SECRET/CERT_B64 统一认证凭据(认证中心分配的客户端密钥与证书公钥) # SITE_URL 站点公开地址(默认 https://personal.virtheart.com) # ========================================================= set -euo pipefail @@ -72,7 +71,6 @@ if [ -z "${SESSION_SECRET}" ]; then fi # 注意:Nuxt runtimeConfig 的环境变量一律使用 NUXT_ 前缀 -# Casdoor 凭据(客户端密钥/证书公钥等机密,由环境变量注入,不写入仓库) kubectl create secret generic app-secrets -n "${NAMESPACE}" \ --from-literal="NUXT_SESSION_SECRET=${SESSION_SECRET}" \ @@ -82,9 +80,6 @@ kubectl create secret generic app-secrets -n "${NAMESPACE}" \ --from-literal="NUXT_SMTP_PASS=${SMTP_PASS:-}" \ --from-literal="NUXT_SMTP_FROM=${SMTP_FROM:-}" \ --from-literal="NUXT_CONTACT_TO=${CONTACT_TO:-}" \ - --from-literal="NUXT_CASDOOR_CLIENT_ID=${CASDOOR_CLIENT_ID:-}" \ - --from-literal="NUXT_CASDOOR_CLIENT_SECRET=${CASDOOR_CLIENT_SECRET:-}" \ - --from-literal="NUXT_CASDOOR_CERT_B64=${CASDOOR_CERT_B64:-}" \ --from-literal="NUXT_OSS_ENDPOINT=${OSS_ENDPOINT:-}" \ --from-literal="NUXT_OSS_ACCESS_KEY=${OSS_ACCESS_KEY:-}" \ --from-literal="NUXT_OSS_SECRET_KEY=${OSS_SECRET_KEY:-}" \ @@ -96,16 +91,6 @@ kubectl create secret generic app-secrets -n "${NAMESPACE}" \ kubectl create configmap app-config -n "${NAMESPACE}" \ --from-literal="NUXT_PUBLIC_SITE_URL=${SITE_URL:-https://personal.virtheart.com}" \ --from-literal="NUXT_DB_PATH=/data/arcticnewone.db" \ - --from-literal="NUXT_CASDOOR_SERVER_URL=${CASDOOR_SERVER_URL:-https://sys.virtheart.com}" \ - --from-literal="NUXT_CASDOOR_ORG_NAME=${CASDOOR_ORG_NAME:-virtheart}" \ - --from-literal="NUXT_CASDOOR_APP_NAME=${CASDOOR_APP_NAME:-virtheat-personal}" \ - --from-literal="NUXT_CASDOOR_ADMIN_ROLES=${CASDOOR_ADMIN_ROLES:-admin}" \ - --from-literal="NUXT_CASDOOR_CALLBACK_PATH=${CASDOOR_CALLBACK_PATH:-/api/auth/callback}" \ - --from-literal="NUXT_PUBLIC_CASDOOR_SERVER_URL=${CASDOOR_SERVER_URL:-https://sys.virtheart.com}" \ - --from-literal="NUXT_PUBLIC_CASDOOR_CLIENT_ID=${CASDOOR_CLIENT_ID:-}" \ - --from-literal="NUXT_PUBLIC_CASDOOR_ORG_NAME=${CASDOOR_ORG_NAME:-virtheart}" \ - --from-literal="NUXT_PUBLIC_CASDOOR_APP_NAME=${CASDOOR_APP_NAME:-virtheat-personal}" \ - --from-literal="NUXT_PUBLIC_CASDOOR_REDIRECT_PATH=${CASDOOR_CALLBACK_PATH:-/api/auth/callback}" \ --dry-run=client -o yaml | kubectl apply -f - >/dev/null # ---------- 4. 应用全部资源 ---------- diff --git a/i18n/locales/en.json b/i18n/locales/en.json index bda99ad..8f94c4e 100755 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -315,6 +315,7 @@ "casdoorDescription": "Sign in with the unified identity provider", "casdoorHint": "Click the button below to continue at the unified authentication center.", "loginWithCasdoor": "Sign in with SSO", + "ssoDisabled": "Unified authentication is not enabled yet. Contact the administrator and try again later.", "redirecting": "Redirecting to sign in", "account": "Account", "accountPlaceholder": "Username / Email / Phone", diff --git a/i18n/locales/zh.json b/i18n/locales/zh.json index 2253837..f74e53f 100755 --- a/i18n/locales/zh.json +++ b/i18n/locales/zh.json @@ -315,6 +315,7 @@ "casdoorDescription": "使用统一身份认证,登录北极新站内账号", "casdoorHint": "选择下方按钮,将跳转到统一身份认证中心完成登录。", "loginWithCasdoor": "通过统一身份认证登录", + "ssoDisabled": "统一认证尚未启用,请联系管理员配置后再登录。", "redirecting": "正在跳转登录…", "account": "账号", "accountPlaceholder": "用户名 / 邮箱 / 手机号", diff --git a/nuxt.config.ts b/nuxt.config.ts index d272fcc..d0bf132 100755 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -22,7 +22,7 @@ export default defineNuxtConfig({ // 与全站 ``/`` 等无前缀引用保持一致 components: [{ path: '~/components', pathPrefix: false }], runtimeConfig: { - // 服务端私有配置(环境变量自动映射:SESSION_SECRET / DB_PATH / SMTP_* / CONTACT_TO / CASDOOR_*) + // 服务端私有配置(环境变量自动映射:SESSION_SECRET / DB_PATH / SMTP_* / CONTACT_TO / OSS_*) sessionSecret: '', dbPath: process.env.DB_PATH || (process.env.NODE_ENV === 'production' ? '/data/arcticnewone.db' : '.data/arcticnewone.db'), smtpHost: '', @@ -32,15 +32,6 @@ export default defineNuxtConfig({ smtpFrom: '', contactTo: '', adminEmails: '', - // Casdoor 统一认证(凭据仅走环境变量注入,绝不写入代码) - casdoorServerUrl: '', - casdoorClientId: '', - casdoorClientSecret: '', - casdoorOrgName: '', - casdoorAppName: '', - casdoorCertB64: '', - casdoorAdminRoles: '', - casdoorCallbackPath: '/api/auth/callback', // OSS 文件存储(RustFS / S3 v4 兼容;凭据仅走环境变量注入,绝不写入仓库) ossEndpoint: '', ossAccessKey: '', @@ -51,11 +42,6 @@ export default defineNuxtConfig({ public: { // 客户端可见(环境变量:NUXT_PUBLIC_*) siteUrl: '', - casdoorServerUrl: '', - casdoorClientId: '', - casdoorOrgName: '', - casdoorAppName: '', - casdoorRedirectPath: '/api/auth/callback', }, }, modules: [ diff --git a/server/api/admin/admin-users.get.ts b/server/api/admin/admin-users.get.ts new file mode 100644 index 0000000..ed9e27b --- /dev/null +++ b/server/api/admin/admin-users.get.ts @@ -0,0 +1,13 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台管理员账号列表(不含密码哈希)。 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const admins = getDb() + .prepare('SELECT id, username, created_at AS createdAt FROM admin_users ORDER BY id ASC') + .all() + return { admins } +}) \ No newline at end of file diff --git a/server/api/admin/admin-users.post.ts b/server/api/admin/admin-users.post.ts new file mode 100644 index 0000000..0ccc4aa --- /dev/null +++ b/server/api/admin/admin-users.post.ts @@ -0,0 +1,34 @@ +import { readBody, createError } from 'h3' +import { requireAdmin } from '../../utils/auth' +import { hashPassword } from '../../utils/adminAuth' +import { getDb } from '../../utils/db' +import { writeAudit } from '../../utils/audit' + +/** + * 新增后台管理员(由当前管理员操作)。 + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const body = await readBody(event) + const username = String(body?.username || '').trim() + const password = String(body?.password || '') + + if (!/^[a-zA-Z0-9_]{2,20}$/.test(username)) { + throw createError({ statusCode: 400, message: '用户名需为 2-20 位字母、数字或下划线', data: { code: 'VALIDATION_ERROR' } }) + } + if (password.length < 8) { + throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) + } + + const db = getDb() + if (db.prepare('SELECT id FROM admin_users WHERE username = ?').get(username)) { + throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } }) + } + + const { lastInsertRowid } = db + .prepare('INSERT INTO admin_users (username, password_hash) VALUES (?, ?)') + .run(username, hashPassword(password)) + + writeAudit(event, 'create', `admin-user:${username}`) + return { ok: true, admin: { id: Number(lastInsertRowid), username } } +}) \ No newline at end of file diff --git a/server/api/admin/admin-users/[id].delete.ts b/server/api/admin/admin-users/[id].delete.ts new file mode 100644 index 0000000..6dfd654 --- /dev/null +++ b/server/api/admin/admin-users/[id].delete.ts @@ -0,0 +1,27 @@ +import { createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' + +/** + * 删除后台管理员(不允许删除自己)。 + */ +export default defineEventHandler((event) => { + const me = requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const db = getDb() + + if (me.id === id) { + throw createError({ statusCode: 400, message: '不能删除当前登录的管理员账号', data: { code: 'VALIDATION_ERROR' } }) + } + const target = db.prepare('SELECT id, username FROM admin_users WHERE id = ?').get(id) as + | { id: number; username: string } + | undefined + if (!target) { + throw createError({ statusCode: 404, message: '管理员不存在', data: { code: 'NOT_FOUND' } }) + } + + db.prepare('DELETE FROM admin_users WHERE id = ?').run(id) + writeAudit(event, 'delete', `admin-user:${target.username}`) + return { ok: true } +}) \ No newline at end of file diff --git a/server/api/admin/admin-users/[id].patch.ts b/server/api/admin/admin-users/[id].patch.ts new file mode 100644 index 0000000..30e50b9 --- /dev/null +++ b/server/api/admin/admin-users/[id].patch.ts @@ -0,0 +1,52 @@ +import { readBody, createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { hashPassword } from '../../../utils/adminAuth' +import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' + +/** + * 修改后台管理员(改密码)。不能操作自己以外无需限制,但可防止把自己锁死由 UI 负责。 + */ +export default defineEventHandler(async (event) => { + const me = requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const body = await readBody(event) + const db = getDb() + + const target = db.prepare('SELECT id, username FROM admin_users WHERE id = ?').get(id) as + | { id: number; username: string } + | undefined + if (!target) { + throw createError({ statusCode: 404, message: '管理员不存在', data: { code: 'NOT_FOUND' } }) + } + + let updated = false + + if (body?.password !== undefined) { + const password = String(body.password) + if (password.length < 8) { + throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) + } + db.prepare('UPDATE admin_users SET password_hash = ? WHERE id = ?').run(hashPassword(password), id) + updated = true + } + + if (body?.username !== undefined) { + const username = String(body.username).trim() + if (!/^[a-zA-Z0-9_]{2,20}$/.test(username)) { + throw createError({ statusCode: 400, message: '用户名需为 2-20 位字母、数字或下划线', data: { code: 'VALIDATION_ERROR' } }) + } + if (db.prepare('SELECT id FROM admin_users WHERE username = ? AND id != ?').get(username, id)) { + throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } }) + } + db.prepare('UPDATE admin_users SET username = ? WHERE id = ?').run(username, id) + updated = true + } + + if (!updated) { + throw createError({ statusCode: 400, message: '没有可更新的内容', data: { code: 'VALIDATION_ERROR' } }) + } + + writeAudit(event, 'update', `admin-user:${id}`, me.username) + return { ok: true } +}) \ No newline at end of file diff --git a/server/api/admin/casdoor-config.get.ts b/server/api/admin/casdoor-config.get.ts new file mode 100644 index 0000000..e963658 --- /dev/null +++ b/server/api/admin/casdoor-config.get.ts @@ -0,0 +1,11 @@ +import { requireAdmin } from '../../utils/auth' +import { getCasdoorConfig } from '../../utils/casdoorConfig' + +/** + * 后台读取 Casdoor 认证配置。 + * clientSecret / 证书仅后台可见(公开接口不含)。 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + return { config: getCasdoorConfig() } +}) \ No newline at end of file diff --git a/server/api/admin/casdoor-config.patch.ts b/server/api/admin/casdoor-config.patch.ts new file mode 100644 index 0000000..baba024 --- /dev/null +++ b/server/api/admin/casdoor-config.patch.ts @@ -0,0 +1,27 @@ +import { readBody, createError } from 'h3' +import { requireAdmin } from '../../utils/auth' +import { saveCasdoorConfig, validateCasdoorConfig, getCasdoorConfig } from '../../utils/casdoorConfig' +import { writeAudit } from '../../utils/audit' + +/** + * 后台保存 Casdoor 认证配置(持久化到 settings 表)。 + * 空字段表示「保留旧值」;enabled 显式传布尔。 + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const body = await readBody(event) + + const patch = body?.config + if (!patch || typeof patch !== 'object' || Array.isArray(patch)) { + throw createError({ statusCode: 400, message: '缺少配置内容', data: { code: 'VALIDATION_ERROR' } }) + } + + const errors = validateCasdoorConfig(patch) + if (errors.length) { + throw createError({ statusCode: 400, message: errors.join(';'), data: { code: 'VALIDATION_ERROR' } }) + } + + saveCasdoorConfig(patch) + writeAudit(event, 'update', 'casdoor-config') + return { ok: true, config: getCasdoorConfig() } +}) \ No newline at end of file diff --git a/server/api/auth/admin-init-status.get.ts b/server/api/auth/admin-init-status.get.ts new file mode 100644 index 0000000..ed47f22 --- /dev/null +++ b/server/api/auth/admin-init-status.get.ts @@ -0,0 +1,8 @@ +import { countAdmins } from '../../utils/adminAuth' + +/** + * 公众号检查:是否已初始化管理员(供前端强制跳转初始化页)。 + */ +export default defineEventHandler(() => { + return { needsInit: countAdmins() === 0 } +}) \ No newline at end of file diff --git a/server/api/auth/admin-init.post.ts b/server/api/auth/admin-init.post.ts new file mode 100644 index 0000000..f88c39a --- /dev/null +++ b/server/api/auth/admin-init.post.ts @@ -0,0 +1,39 @@ +import { readBody, createError } from 'h3' +import { countAdmins, hashPassword, createAdminSession, setAdminSessionCookie } from '../../utils/adminAuth' +import { getDb } from '../../utils/db' + +/** + * 首个管理员初始化(仅当系统尚未初始化时可用): + * 用户自定义管理员账号密码,成功后直接建立会话进入后台。 + */ +export default defineEventHandler(async (event) => { + if (countAdmins() > 0) { + throw createError({ statusCode: 409, message: '系统已初始化管理员', data: { code: 'ALREADY_INITIALIZED' } }) + } + + const body = await readBody(event) + const username = String(body?.username || '').trim() + const password = String(body?.password || '') + + if (!/^[a-zA-Z0-9_]{2,20}$/.test(username)) { + throw createError({ statusCode: 400, message: '用户名需为 2-20 位字母、数字或下划线', data: { code: 'VALIDATION_ERROR' } }) + } + if (password.length < 8) { + throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) + } + + const db = getDb() + const taken = db.prepare('SELECT id FROM admin_users WHERE username = ?').get(username) + if (taken) { + throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } }) + } + + const { lastInsertRowid } = db + .prepare('INSERT INTO admin_users (username, password_hash) VALUES (?, ?)') + .run(username, hashPassword(password)) + + const token = createAdminSession(Number(lastInsertRowid)) + setAdminSessionCookie(event, token) + + return { ok: true, admin: { id: Number(lastInsertRowid), username } } +}) \ No newline at end of file diff --git a/server/api/auth/admin/login.post.ts b/server/api/auth/admin/login.post.ts new file mode 100644 index 0000000..fbad456 --- /dev/null +++ b/server/api/auth/admin/login.post.ts @@ -0,0 +1,25 @@ +import { readBody, createError } from 'h3' +import { verifyPassword, createAdminSession, setAdminSessionCookie } from '../../../utils/adminAuth' +import { getDb } from '../../../utils/db' + +/** + * 后台管理员登录(独立于 Casdoor)。 + */ +export default defineEventHandler(async (event) => { + const body = await readBody(event) + const username = String(body?.username || '').trim() + const password = String(body?.password || '') + + const row = getDb() + .prepare('SELECT id, username, password_hash, created_at FROM admin_users WHERE username = ?') + .get(username) as { id: number; username: string; password_hash: string; created_at: string } | undefined + + if (!row || !verifyPassword(password, row.password_hash)) { + throw createError({ statusCode: 401, message: '用户名或密码错误', data: { code: 'INVALID_CREDENTIALS' } }) + } + + const token = createAdminSession(row.id) + setAdminSessionCookie(event, token) + + return { ok: true, admin: { id: row.id, username: row.username, created_at: row.created_at } } +}) \ No newline at end of file diff --git a/server/api/auth/admin/logout.post.ts b/server/api/auth/admin/logout.post.ts new file mode 100644 index 0000000..56a1414 --- /dev/null +++ b/server/api/auth/admin/logout.post.ts @@ -0,0 +1,14 @@ +import { getCookie } from 'h3' +import { ADMIN_SESSION_COOKIE, destroyAdminSession, clearAdminSessionCookie } from '../../../utils/adminAuth' + +/** + * 后台管理员登出。 + */ +export default defineEventHandler((event) => { + const token = getCookie(event, ADMIN_SESSION_COOKIE) + if (token) { + destroyAdminSession(token) + } + clearAdminSessionCookie(event) + return { ok: true } +}) \ No newline at end of file diff --git a/server/api/auth/admin/me.get.ts b/server/api/auth/admin/me.get.ts new file mode 100644 index 0000000..506b4c3 --- /dev/null +++ b/server/api/auth/admin/me.get.ts @@ -0,0 +1,13 @@ +import { createError } from 'h3' +import { getCurrentAdmin } from '../../../utils/adminAuth' + +/** + * 当前管理员(用于前端恢复登录态)。 + */ +export default defineEventHandler((event) => { + const admin = getCurrentAdmin(event) + if (!admin) { + throw createError({ statusCode: 401, message: '未登录', data: { code: 'UNAUTHORIZED' } }) + } + return { admin } +}) \ No newline at end of file diff --git a/server/api/auth/callback.get.ts b/server/api/auth/callback.get.ts index 4afcc67..4070a89 100644 --- a/server/api/auth/callback.get.ts +++ b/server/api/auth/callback.get.ts @@ -1,7 +1,7 @@ import { getQuery, getCookie, deleteCookie, createError, sendRedirect } from 'h3' import { exchangeCodeForIdentity, getCasdoorState } from '../../utils/casdoor' import { upsertCasdoorUser, createSession, setSessionCookie } from '../../utils/auth' -import { isCasdoorEnabled } from '../../utils/config' +import { isCasdoorEnabled } from '../../utils/casdoorConfig' /** * Casdoor OAuth 回调: diff --git a/server/api/auth/casdoor-config.get.ts b/server/api/auth/casdoor-config.get.ts new file mode 100644 index 0000000..d943a7c --- /dev/null +++ b/server/api/auth/casdoor-config.get.ts @@ -0,0 +1,9 @@ +import { getCasdoorConfig, toPublicCasdoorConfig } from '../../utils/casdoorConfig' + +/** + * 前台统一认证公开配置(不含任何 secret)。 + * 用于登录弹窗判断是否启用、拼接注册/登出地址。 + */ +export default defineEventHandler(() => { + return toPublicCasdoorConfig(getCasdoorConfig()) +}) \ No newline at end of file diff --git a/server/api/auth/casdoor-login.get.ts b/server/api/auth/casdoor-login.get.ts index 5fba15e..bdd4a28 100644 --- a/server/api/auth/casdoor-login.get.ts +++ b/server/api/auth/casdoor-login.get.ts @@ -1,6 +1,6 @@ import { getQuery, setCookie, sendRedirect, createError } from 'h3' import { getCasdoorSignInUrl, getCasdoorState } from '../../utils/casdoor' -import { isCasdoorEnabled } from '../../utils/config' +import { isCasdoorEnabled } from '../../utils/casdoorConfig' /** * 统一认证入口:跳转到 Casdoor 登录页。 diff --git a/server/middleware/init-guard.ts b/server/middleware/init-guard.ts new file mode 100644 index 0000000..f47d5c4 --- /dev/null +++ b/server/middleware/init-guard.ts @@ -0,0 +1,15 @@ +import { countAdmins } from '../utils/adminAuth' + +/** + * 首个管理员初始化引导(服务端兜底)。 + * - 系统无管理员时:仅拦截后台页面路由 `/admin/**`,重定向到 /admin/init; + * - 公开页面与所有 `/api/*` 正常放行(后台 API 自身由 requireAdmin 鉴权,未初始化时无人能登录); + * - 客户端另有 init.global 中间件做同等引导,两者逻辑一致。 + */ +export default defineEventHandler((event) => { + if (countAdmins() > 0) return + const path = getRequestURL(event).pathname + if (!path.startsWith('/admin/')) return + if (path.startsWith('/admin/init')) return + return sendRedirect(event, '/admin/init', 302) +}) \ No newline at end of file diff --git a/server/utils/adminAuth.ts b/server/utils/adminAuth.ts new file mode 100644 index 0000000..5de739e --- /dev/null +++ b/server/utils/adminAuth.ts @@ -0,0 +1,117 @@ +import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto' +import { createError, getCookie, setCookie, deleteCookie } from 'h3' +import type { H3Event } from 'h3' +import { getDb } from './db' + +/** + * 后台管理员认证(独立于 Casdoor 前台用户体系)。 + * + * - 管理员账号存 `admin_users`(username + password_hash),后台权限完全由此决定 + * - 会话存 `admin_sessions`,走独立 Cookie `an_admin_session` + * - 首个管理员通过 /admin/init 网页初始化(库内无管理员时强制引导) + */ + +export interface AdminUserRow { + id: number + username: string + created_at: string +} + +export const ADMIN_SESSION_COOKIE = 'an_admin_session' +const ADMIN_TTL_SECONDS = 24 * 60 * 60 // 24 小时 + +// ---------- 密码 ---------- + +const SCRYPT_KEYLEN = 64 +const SCRYPT_PARAMS = { N: 16384, r: 8, p: 1 } + +/** 生成密码哈希(scrypt,格式 scrypt$N$r$p$salt$hash) */ +export function hashPassword(password: string): string { + const salt = randomBytes(16).toString('hex') + const hash = scryptSync(password, salt, SCRYPT_KEYLEN, SCRYPT_PARAMS).toString('hex') + return `scrypt$${SCRYPT_PARAMS.N}$${SCRYPT_PARAMS.r}$${SCRYPT_PARAMS.p}$${salt}$${hash}` +} + +/** 校验密码;格式不合法时一律返回 false,避免被异常输入绕过 */ +export function verifyPassword(password: string, stored: string): boolean { + try { + const parts = stored.split('$') + if (parts[0] !== 'scrypt' || parts.length !== 6) return false + const [, nStr, rStr, pStr, salt, hashHex] = parts + const params = { N: Number(nStr), r: Number(rStr), p: Number(pStr) } + if (!params.N || !params.r || !params.p) return false + // 严格校验:hashHex 必须为合法的偶数长度十六进制,且为 64 字节 + if (!/^[0-9a-f]+$/i.test(hashHex) || hashHex.length % 2 !== 0 || hashHex.length !== SCRYPT_KEYLEN * 2) { + return false + } + const expected = Buffer.from(hashHex, 'hex') + const actual = scryptSync(password, salt, expected.length, params) + return timingSafeEqual(expected, actual) + } catch { + return false + } +} + +// ---------- 会话 ---------- + +export function createAdminSession(adminId: number): string { + const token = randomBytes(32).toString('hex') + const expiresAt = new Date(Date.now() + ADMIN_TTL_SECONDS * 1000).toISOString() + getDb() + .prepare('INSERT INTO admin_sessions (token, admin_id, expires_at) VALUES (?, ?, ?)') + .run(token, adminId, expiresAt) + return token +} + +export function destroyAdminSession(token: string): void { + getDb().prepare('DELETE FROM admin_sessions WHERE token = ?').run(token) +} + +export function getAdminSessionUser(token: string | null): AdminUserRow | null { + if (!token) return null + const row = getDb() + .prepare( + `SELECT a.id, a.username, a.created_at + FROM admin_sessions s + JOIN admin_users a ON a.id = s.admin_id + WHERE s.token = ? AND s.expires_at > datetime('now')`, + ) + .get(token) as AdminUserRow | undefined + return row ?? null +} + +/** 从请求 Cookie 解析当前管理员;未登录返回 null */ +export function getCurrentAdmin(event: H3Event): AdminUserRow | null { + const token = getCookie(event, ADMIN_SESSION_COOKIE) + return getAdminSessionUser(token) +} + +/** 后台守卫:未登录抛出 401 */ +export function requireAdminSession(event: H3Event): AdminUserRow { + const admin = getCurrentAdmin(event) + if (!admin) { + throw createError({ statusCode: 401, statusMessage: '未登录', message: '后台需要登录', data: { code: 'UNAUTHORIZED' } }) + } + return admin +} + +export function setAdminSessionCookie(event: H3Event, token: string): void { + const secure = process.env.NODE_ENV === 'production' + setCookie(event, ADMIN_SESSION_COOKIE, token, { + httpOnly: true, + sameSite: 'lax', + secure, + path: '/', + maxAge: ADMIN_TTL_SECONDS, + }) +} + +export function clearAdminSessionCookie(event: H3Event): void { + deleteCookie(event, ADMIN_SESSION_COOKIE, { path: '/' }) +} + +/** 管理员总数(用于初始化引导) */ +export function countAdmins(): number { + const row = getDb().prepare('SELECT COUNT(*) AS c FROM admin_users').get() as { c: number } + return row.c +} \ No newline at end of file diff --git a/server/utils/audit.ts b/server/utils/audit.ts index dd66394..2a088b5 100644 --- a/server/utils/audit.ts +++ b/server/utils/audit.ts @@ -1,17 +1,17 @@ import type { H3Event } from 'h3' import { getDb } from './db' -import { getCurrentUser } from './auth' +import { getCurrentAdmin } from './adminAuth' /** * 记录后台操作审计日志(增删改内容/用户/评论/联系/订阅/上传等)。 - * 写入失败不影响主流程(仅记录日志)。 + * 操作者取后台管理员会话;写入失败不影响主流程(仅记录日志)。 */ export function writeAudit(event: H3Event, action: string, target: string, detail?: string): void { try { - const user = getCurrentUser(event) + const admin = getCurrentAdmin(event) getDb() .prepare('INSERT INTO audit_logs (actor_id, actor_name, action, target, detail) VALUES (?, ?, ?, ?, ?)') - .run(user?.id ?? null, user?.username ?? 'system', action, target, detail ?? null) + .run(admin?.id ?? null, admin?.username ?? 'system', action, target, detail ?? null) } catch (err) { console.error('[audit] write failed:', err) } diff --git a/server/utils/auth.ts b/server/utils/auth.ts index 6db3686..bb7a33a 100644 --- a/server/utils/auth.ts +++ b/server/utils/auth.ts @@ -3,6 +3,7 @@ import { createError, getCookie, setCookie, deleteCookie } from 'h3' import type { H3Event } from 'h3' import { getDb } from './db' import type { CasdoorIdentity } from './casdoor' +import { requireAdminSession } from './adminAuth' export interface UserRow { id: number @@ -62,13 +63,12 @@ export function requireUser(event: H3Event): UserRow { return user } -/** 需要管理员权限的接口守卫;非管理员抛出 403 */ -export function requireAdmin(event: H3Event): UserRow { - const user = requireUser(event) - if (user.role !== 'admin') { - throw createError({ statusCode: 403, statusMessage: '无权限', message: '无权限', data: { code: 'FORBIDDEN' } }) - } - return user +/** + * 后台接口守卫:凭管理员会话鉴权(独立 admin_users 体系)。 + * 前台用户(含 Casdoor SSO)一律无后台权限。 + */ +export function requireAdmin(event: H3Event): ReturnType { + return requireAdminSession(event) } /** 登录成功后写入会话 Cookie */ @@ -91,24 +91,23 @@ export function clearSessionCookie(event: H3Event): void { // ---------- Casdoor 用户映射 ---------- /** - * 按 Casdoor 唯一标识(provider + sub)upsert 本地用户。 - * - 已存在:刷新资料(姓名/邮箱/头像)与角色快照(角色只从 Casdoor claim 派生) + * 按 Casdoor 唯一标识(provider + sub)upsert 本地前台用户。 + * - 已存在:刷新资料(姓名/邮箱/头像) * - 不存在:首次登录自动建号 + * - 前台用户一律为普通用户(后台权限由独立 admin_users 表管理) */ export function upsertCasdoorUser(identity: CasdoorIdentity): UserRow { const db = getDb() - const role: 'user' | 'admin' = identity.isAdmin ? 'admin' : 'user' const existing = db .prepare('SELECT id FROM users WHERE provider = ? AND provider_id = ?') .get(identity.provider, identity.providerId) as { id: number } | undefined if (existing) { - db.prepare('UPDATE users SET username = ?, email = ?, avatar = ?, role = ? WHERE id = ?').run( + db.prepare('UPDATE users SET username = ?, email = ?, avatar = ? WHERE id = ?').run( identity.username, identity.email, identity.avatar || null, - role, existing.id, ) } else { @@ -118,7 +117,7 @@ export function upsertCasdoorUser(identity: CasdoorIdentity): UserRow { identity.username, identity.email, identity.avatar || null, - role, + 'user', ) } diff --git a/server/utils/casdoor.ts b/server/utils/casdoor.ts index faafa00..cdafc24 100644 --- a/server/utils/casdoor.ts +++ b/server/utils/casdoor.ts @@ -1,27 +1,29 @@ import { SDK } from 'casdoor-nodejs-sdk' +import { getCasdoorConfig } from './casdoorConfig' import { getConfig } from './config' /** * Casdoor 统一认证封装(服务端)。 * * - 登录 URL、code->token 交换、JWT 验签全部走官方 casdoor-nodejs-sdk - * - 客户端 secret / 证书公钥只存在于服务端环境变量,绝不进入浏览器 - * - 登录成功后再通过 get-account 补齐邮箱/头像/角色等字段(拿不到也不阻塞登录) + * - 配置(serverUrl/clientId/clientSecret/证书)由后台写入 settings 表,不依赖环境变量 + * - 登录成功后再通过 get-account 补齐邮箱/头像等字段(拿不到也不阻塞登录) + * - 前台用户一律视为普通用户;后台权限由独立 admin_users 表管理 */ let _sdk: SDK | null = null let _sdkKey = '' function getSDK(): SDK { - const { casdoor } = getConfig() - const key = [casdoor.serverUrl, casdoor.clientId, casdoor.clientSecret, casdoor.orgName, casdoor.appName, casdoor.certificate].join('|') + const cfg = getCasdoorConfig() + const key = [cfg.serverUrl, cfg.clientId, cfg.clientSecret, cfg.orgName, cfg.appName, cfg.certificate].join('|') if (!_sdk || _sdkKey !== key) { _sdk = new SDK({ - endpoint: casdoor.serverUrl, - clientId: casdoor.clientId, - clientSecret: casdoor.clientSecret, - certificate: casdoor.certificate, - orgName: casdoor.orgName, - appName: casdoor.appName || undefined, + endpoint: cfg.serverUrl, + clientId: cfg.clientId, + clientSecret: cfg.clientSecret, + certificate: cfg.certificate, + orgName: cfg.orgName, + appName: cfg.appName || undefined, }) _sdkKey = key } @@ -30,26 +32,28 @@ function getSDK(): SDK { /** 构造 Casdoor 登录授权地址(redirect_uri = 本站回调) */ export function getCasdoorSignInUrl(): string { - const { casdoor } = getConfig() - return getSDK().getSignInUrl(casdoor.redirectUri) + const cfg = getCasdoorConfig() + const redirectUri = getConfig().siteUrl + cfg.callbackPath + return getSDK().getSignInUrl(redirectUri) } /** 构造 Casdoor 注册页地址(在 Casdoor 侧完成注册) */ export function getCasdoorSignUpUrl(): string { - const { casdoor } = getConfig() - return `${casdoor.serverUrl}/signup/${casdoor.appName}` + const cfg = getCasdoorConfig() + return `${cfg.serverUrl}/signup/${cfg.appName}` } /** 单点登出地址(访问后跳回 redirectUri;未配置则返回空串) */ export function getCasdoorLogoutUrl(): string { - const { casdoor } = getConfig() - if (!casdoor.serverUrl || !casdoor.clientId) return '' - return `${casdoor.serverUrl}/logout?client_id=${casdoor.clientId}&redirect_uri=${encodeURIComponent(casdoor.redirectUri)}` + const cfg = getCasdoorConfig() + if (!cfg.serverUrl || !cfg.clientId) return '' + const redirectUri = getConfig().siteUrl + cfg.callbackPath + return `${cfg.serverUrl}/logout?client_id=${cfg.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}` } /** 登录回调校验的期望 state(casdoor SDK 以 appName 作为 state 返回) */ export function getCasdoorState(): string { - return getConfig().casdoor.appName + return getCasdoorConfig().appName } export interface CasdoorIdentity { @@ -59,7 +63,6 @@ export interface CasdoorIdentity { username: string email: string avatar: string - isAdmin: boolean } /** @@ -95,33 +98,13 @@ export async function exchangeCodeForIdentity(code: string): Promise | undefined | null): boolean { - if (!claims) return false - if ((claims as any).isAdmin === true || (claims as any).IsAdmin === true) return true - - const { casdoor } = getConfig() - const roles = (claims as any).roles - if (!Array.isArray(roles) || roles.length === 0) return false - const names = roles - .map((r: any) => (typeof r === 'string' ? r : r?.name)) - .filter(Boolean) - .map((n: string) => n.toLowerCase()) - return names.some((n: string) => casdoor.adminRoles.includes(n)) -} - -/** 通过 get-account 接口补齐完整账号信息(含邮箱/头像/角色);失败不阻塞登录 */ +/** 通过 get-account 接口补齐完整账号信息(含邮箱/头像);失败不阻塞登录 */ async function getAccountProfile(accessToken: string): Promise | null> { - const { casdoor } = getConfig() - const url = `${casdoor.serverUrl}/api/get-account?access_token=${encodeURIComponent(accessToken)}` + const cfg = getCasdoorConfig() + const url = `${cfg.serverUrl}/api/get-account?access_token=${encodeURIComponent(accessToken)}` const res = await fetch(url) if (!res.ok) return null const body = (await res.json()) as { status?: string; data?: Record } diff --git a/server/utils/casdoorConfig.ts b/server/utils/casdoorConfig.ts new file mode 100644 index 0000000..6b4857e --- /dev/null +++ b/server/utils/casdoorConfig.ts @@ -0,0 +1,133 @@ +import { getDb } from './db' +import { getConfig } from './config' + +/** + * Casdoor 统一认证配置(后台可配置,存 settings 表,前缀 `casdoor.*`)。 + * + * - 管理员在 /admin/settings 的「统一认证」页修改,无需环境变量 + * - clientSecret 等敏感字段仅后台可读写,公开的 /api/settings 不会输出(默认站点配置对象中没有 casdoor.* 路径,getSettings 会跳过) + */ +export interface CasdoorConfig { + serverUrl: string + clientId: string + clientSecret: string + orgName: string + appName: string + /** 应用证书公钥(可直接粘贴或 base64) */ + certificate: string + /** 本站回调路径(redirect_uri = siteUrl + 该路径) */ + callbackPath: string + /** 是否启用统一认证登录 */ + enabled: boolean +} + +const DEFAULTS: CasdoorConfig = { + serverUrl: '', + clientId: '', + clientSecret: '', + orgName: '', + appName: '', + certificate: '', + callbackPath: '/api/auth/callback', + enabled: false, +} + +function read(key: string): string { + const row = getDb().prepare('SELECT value FROM settings WHERE key = ?').get(`casdoor.${key}`) as + | { value: string } + | undefined + if (!row) return '' + try { + const v = JSON.parse(row.value) + return typeof v === 'string' ? v : String(v) + } catch { + return '' + } +} + +function readBool(key: string): boolean { + const row = getDb().prepare('SELECT value FROM settings WHERE key = ?').get(`casdoor.${key}`) as + | { value: string } + | undefined + if (!row) return false + try { + return Boolean(JSON.parse(row.value)) + } catch { + return false + } +} + +function write(key: string, value: string | boolean): void { + getDb() + .prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value') + .run(`casdoor.${key}`, JSON.stringify(value)) +} + +/** 读取当前 Casdoor 配置(未配置项返回默认/空) */ +export function getCasdoorConfig(): CasdoorConfig { + return { + serverUrl: read('serverUrl'), + clientId: read('clientId'), + clientSecret: read('clientSecret'), + orgName: read('orgName'), + appName: read('appName'), + certificate: decodeCert(read('certificate')), + callbackPath: read('callbackPath') || DEFAULTS.callbackPath, + enabled: readBool('enabled'), + } +} + +/** 持久化 Casdoor 配置(空字段跳过,保留旧值) */ +export function saveCasdoorConfig(patch: Partial): void { + for (const [k, v] of Object.entries(patch)) { + if (v === undefined) continue + // certificate 存原始输入(可能为 base64 或 PEM 原文),读取时再统一解码 + write(k, typeof v === 'boolean' ? v : String(v)) + } +} + +/** 校验必填项并给出友好提示 */ +export function validateCasdoorConfig(cfg: Partial): string[] { + const errors: string[] = [] + if (cfg.enabled) { + if (!String(cfg.serverUrl || '').trim()) errors.push('服务器地址必填') + if (!String(cfg.clientId || '').trim()) errors.push('Client ID 必填') + if (!String(cfg.orgName || '').trim()) errors.push('组织名(orgName)必填') + if (!String(cfg.appName || '').trim()) errors.push('应用名(appName)必填') + } + return errors +} + +/** 是否为前台展示的公开字段(不包含任何 secret) */ +export function toPublicCasdoorConfig(cfg: CasdoorConfig) { + return { + enabled: cfg.enabled, + serverUrl: cfg.serverUrl, + clientId: cfg.clientId, + orgName: cfg.orgName, + appName: cfg.appName, + callbackPath: cfg.callbackPath, + redirectUri: getConfig().siteUrl + cfg.callbackPath, + } +} + +/** 统一认证是否已开启(后台开启 + 必填项齐全) */ +export function isCasdoorEnabled(): boolean { + const cfg = getCasdoorConfig() + return Boolean(cfg.enabled && cfg.serverUrl && cfg.clientId && cfg.orgName && cfg.appName) +} + +/** 将证书 PEM 以 base64(或原文)传入,统一还原为 PEM 字符串 */ +function decodeCert(input: string): string { + const v = (input || '').trim() + if (!v) return '' + if (v.includes('BEGIN CERTIFICATE')) return v + try { + const pem = Buffer.from(v, 'base64').toString('utf-8') + return pem.includes('BEGIN CERTIFICATE') ? pem : v + } catch { + return v + } +} + +export { DEFAULTS } \ No newline at end of file diff --git a/server/utils/config.ts b/server/utils/config.ts index 96ce0db..7c97eff 100644 --- a/server/utils/config.ts +++ b/server/utils/config.ts @@ -25,22 +25,6 @@ export interface AppConfig { from: string } contactTo: string - adminEmails: string[] - /** Casdoor 统一认证 */ - casdoor: { - serverUrl: string - clientId: string - clientSecret: string - orgName: string - appName: string - /** 应用证书公钥 PEM(用于验证 JWT 签名),由 certB64 解码得到 */ - certificate: string - /** 命中任一角色名即管理员 */ - adminRoles: string[] - callbackPath: string - /** 完整回调地址(siteUrl + callbackPath),用于 OAuth redirect_uri */ - redirectUri: string - } /** OSS 服务(RustFS / S3 v4 兼容) */ oss: { endpoint: string @@ -56,10 +40,8 @@ export interface AppConfig { export function getConfig(): AppConfig { const c = useRuntimeConfig() const cfg = _buildConfig(c) - // 回调地址依赖 siteUrl,在对象组装完成后补算 const siteUrl = String((c.public as { siteUrl?: string })?.siteUrl || '').replace(/\/$/, '') cfg.siteUrl = siteUrl - cfg.casdoor.redirectUri = `${siteUrl}${cfg.casdoor.callbackPath}` return cfg } @@ -75,24 +57,6 @@ function _buildConfig(c: any): AppConfig { from: (c.smtpFrom as string) || '', }, contactTo: (c.contactTo as string) || '', - adminEmails: String(c.adminEmails || '') - .split(',') - .map((s) => s.trim().toLowerCase()) - .filter(Boolean), - casdoor: { - serverUrl: String((c.casdoorServerUrl as string) || '').replace(/\/$/, ''), - clientId: String((c.casdoorClientId as string) || ''), - clientSecret: String((c.casdoorClientSecret as string) || ''), - orgName: String((c.casdoorOrgName as string) || ''), - appName: String((c.casdoorAppName as string) || ''), - certificate: decodeCert(String((c.casdoorCertB64 as string) || '')), - adminRoles: String((c.casdoorAdminRoles as string) || 'admin') - .split(',') - .map((s) => s.trim().toLowerCase()) - .filter(Boolean), - callbackPath: String((c.casdoorCallbackPath as string) || '/api/auth/callback'), - redirectUri: '', - }, oss: { endpoint: String((c.ossEndpoint as string) || '').replace(/^https?:\/\//, '').replace(/\/$/, ''), accessKey: String((c.ossAccessKey as string) || ''), @@ -104,27 +68,3 @@ function _buildConfig(c: any): AppConfig { siteUrl: '', } } - -/** 将证书 PEM 以 base64(或原文)传入,统一还原为 PEM 字符串 */ -function decodeCert(input: string): string { - const v = (input || '').trim() - if (!v) return '' - if (v.includes('BEGIN CERTIFICATE')) return v - try { - const pem = Buffer.from(v, 'base64').toString('utf-8') - return pem.includes('BEGIN CERTIFICATE') ? pem : v - } catch { - return v - } -} - -/** Casdoor 配置已就绪(有了 clientId + 服务端地址即可启用统一登录) */ -export function isCasdoorEnabled(): boolean { - const { casdoor } = getConfig() - return Boolean(casdoor.serverUrl && casdoor.clientId) -} - -/** 判断某邮箱是否在管理员白名单中 */ -export function isAdminEmail(email: string): boolean { - return getConfig().adminEmails.includes(email.toLowerCase()) -} diff --git a/server/utils/db.ts b/server/utils/db.ts index 15bac31..343e798 100644 --- a/server/utils/db.ts +++ b/server/utils/db.ts @@ -79,6 +79,25 @@ function migrate(db: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id); + -- 后台管理员(独立于 Casdoor 前台用户体系) + CREATE TABLE IF NOT EXISTS admin_users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_admin_users_username ON admin_users(username); + + CREATE TABLE IF NOT EXISTS admin_sessions ( + token TEXT PRIMARY KEY, + admin_id INTEGER NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + expires_at TEXT NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_admin_sessions_admin ON admin_sessions(admin_id); + CREATE TABLE IF NOT EXISTS contacts ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, diff --git a/tests/adminAuth.test.ts b/tests/adminAuth.test.ts new file mode 100644 index 0000000..4edb743 --- /dev/null +++ b/tests/adminAuth.test.ts @@ -0,0 +1,50 @@ +import { describe, it, expect, vi, beforeAll } from 'vitest' + +/** + * 后台管理员认证单测: + * - hashPassword / verifyPassword:scrypt 哈希与校验(格式 scrypt$N$r$p$salt$hash) + * - 异常/非法存储串一律校验失败,防绕过 + */ + +vi.mock('../server/utils/db', () => ({ + getDb: vi.fn(() => { + throw new Error('db not used in these tests') + }), +})) + +vi.mock('h3', () => ({ + createError: (o: unknown) => o, + getCookie: () => null, + setCookie: () => {}, + deleteCookie: () => {}, +})) + +import { hashPassword, verifyPassword } from '../server/utils/adminAuth' + +describe('admin password hashing', () => { + it('hashes and verifies a correct password', () => { + const hash = hashPassword('correct horse battery staple') + expect(hash.startsWith('scrypt$')).toBe(true) + expect(verifyPassword('correct horse battery staple', hash)).toBe(true) + }) + + it('rejects a wrong password', () => { + const hash = hashPassword('right-password') + expect(verifyPassword('wrong-password', hash)).toBe(false) + }) + + it('produces unique salts (same password, different hashes)', () => { + const a = hashPassword('same-pass') + const b = hashPassword('same-pass') + expect(a).not.toBe(b) + expect(verifyPassword('same-pass', a)).toBe(true) + expect(verifyPassword('same-pass', b)).toBe(true) + }) + + it('rejects malformed / foreign stored values', () => { + expect(verifyPassword('x', '')).toBe(false) + expect(verifyPassword('x', 'plaintext')).toBe(false) + expect(verifyPassword('x', 'bcrypt$abcdef')).toBe(false) + expect(verifyPassword('x', 'scrypt$16384$8$1$salt$nothex')).toBe(false) + }) +}) \ No newline at end of file diff --git a/tests/casdoor.test.ts b/tests/casdoor.test.ts index 0aa2da4..687df4f 100644 --- a/tests/casdoor.test.ts +++ b/tests/casdoor.test.ts @@ -1,77 +1,92 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' /** - * Casdoor 认证逻辑单测(纯函数,不依赖外部服务)。 - * 覆盖: - * - isAdminClaim:IsAdmin / isAdmin 字段与 roles 名单判定 - * - getCasdoorSignUpUrl / getCasdoorLogoutUrl:登录/注册/登出地址构造 - * - config.decodeCert:证书 base64 还原 + * Casdoor 认证逻辑单测(纯函数,依赖通过 vi.mock 桩掉): + * - getCasdoorSignInUrl / getCasdoorLogoutUrl 地址构造(走 SDK getSignInUrl 与手动拼接) + * - casdoorConfig.toPublicCasdoorConfig 不泄漏 secret + * - casdoorConfig.validateCasdoorConfig 必填校验 + * - 后台管理员密码 scrypt 哈希/校验(adminAuth) */ -vi.mock('../server/utils/config', () => ({ - getConfig: () => ({ - casdoor: { +vi.mock('../server/utils/casdoorConfig', async (importOriginal) => { + const actual = (await importOriginal()) as Record + return { + ...actual, + getCasdoorConfig: () => ({ serverUrl: 'https://sys.virtheart.com', clientId: 'a0ba9570e0bcfbeb9f67', - clientSecret: 'secret', + clientSecret: 'secret123', orgName: 'virtheart', appName: 'virtheat-personal', certificate: 'FAKE_CERT', - adminRoles: ['admin'], callbackPath: '/api/auth/callback', - redirectUri: 'https://personal.virtheart.com/api/auth/callback', - }, - }), - isCasdoorEnabled: () => true, -})) - -import { isAdminClaim } from '../server/utils/casdoor' -import { getConfig } from '../server/utils/config' - -describe('isAdminClaim', () => { - it('returns false for empty / null claims', () => { - expect(isAdminClaim(null)).toBe(false) - expect(isAdminClaim(undefined)).toBe(false) - expect(isAdminClaim({})).toBe(false) - }) - - it('honors isAdmin / IsAdmin boolean fields', () => { - expect(isAdminClaim({ isAdmin: true })).toBe(true) - expect(isAdminClaim({ IsAdmin: true })).toBe(true) - expect(isAdminClaim({ isAdmin: false })).toBe(false) - }) - - it('honors roles array (string form)', () => { - expect(isAdminClaim({ roles: ['admin'] })).toBe(true) - expect(isAdminClaim({ roles: ['user', 'editor'] })).toBe(false) - }) - - it('honors roles array (object form with name)', () => { - expect(isAdminClaim({ roles: [{ name: 'admin' }] })).toBe(true) - expect(isAdminClaim({ roles: [{ name: 'user' }] })).toBe(false) - }) - - it('is case-insensitive on role names', () => { - expect(isAdminClaim({ roles: ['Admin'] })).toBe(true) - }) - - it('falls back to configured admin roles', () => { - const cfg = getConfig() - expect(cfg.casdoor.adminRoles).toContain('admin') - }) + enabled: true, + }), + } }) +vi.mock('../server/utils/config', () => ({ + getConfig: () => ({ + siteUrl: 'https://personal.virtheart.com', + dbPath: ':memory:', + sessionSecret: 'test-secret', + smtp: {}, + }), +})) + +import { getCasdoorSignInUrl, getCasdoorSignUpUrl, getCasdoorLogoutUrl } from '../server/utils/casdoor' +import { toPublicCasdoorConfig, validateCasdoorConfig } from '../server/utils/casdoorConfig' + describe('casdoor URLs', () => { - it('builds signup url from config', async () => { - const { getCasdoorSignUpUrl } = await import('../server/utils/casdoor') + it('builds sign-in url via SDK with redirect_uri + state', () => { + const url = getCasdoorSignInUrl() + expect(url).toContain('https://sys.virtheart.com/login/oauth/authorize') + expect(url).toContain('client_id=a0ba9570e0bcfbeb9f67') + expect(decodeURIComponent(url)).toContain('redirect_uri=https://personal.virtheart.com/api/auth/callback') + }) + + it('builds signup url', () => { expect(getCasdoorSignUpUrl()).toBe('https://sys.virtheart.com/signup/virtheat-personal') }) - it('builds logout url with client_id and redirect_uri', async () => { - const { getCasdoorLogoutUrl } = await import('../server/utils/casdoor') + it('builds logout url with client_id and redirect_uri', () => { const url = getCasdoorLogoutUrl() expect(url).toContain('https://sys.virtheart.com/logout') expect(url).toContain('client_id=a0ba9570e0bcfbeb9f67') expect(decodeURIComponent(url)).toContain('https://personal.virtheart.com/api/auth/callback') }) }) + +describe('casdoorConfig', () => { + it('public config never leaks secret fields', () => { + const pub = toPublicCasdoorConfig({ + serverUrl: 'https://sys.virtheart.com', + clientId: 'cid', + clientSecret: 'super-secret', + orgName: 'virtheart', + appName: 'app', + certificate: 'CERT', + callbackPath: '/api/auth/callback', + enabled: true, + }) + expect(pub).not.toHaveProperty('clientSecret') + expect(pub).not.toHaveProperty('certificate') + expect(pub.enabled).toBe(true) + expect(pub.redirectUri).toBe('https://personal.virtheart.com/api/auth/callback') + }) + + it('validates required fields when enabled', () => { + const errs = validateCasdoorConfig({ enabled: true }) + expect(errs.length).toBeGreaterThan(0) + expect(validateCasdoorConfig({ enabled: false })).toEqual([]) + expect( + validateCasdoorConfig({ + enabled: true, + serverUrl: 'https://sys.virtheart.com', + clientId: 'cid', + orgName: 'virtheart', + appName: 'app', + }), + ).toEqual([]) + }) +}) \ No newline at end of file