feat(system-admin): implement bootstrap for system admin promotion and enhance system settings management

- Added WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL environment variable to promote a specified user to system admin on startup.
- Introduced a new bootstrap process in `bootstrap.go` to handle the promotion logic.
- Updated `.env.example` to document the new environment variable and its behavior.
- Created new views for managing system administrators and system settings, including listing, promoting, and revoking admin privileges.
- Enhanced the frontend to reflect the new system admin features, including UI elements for admin management and settings configuration.
- Updated API interfaces to support system admin functionalities, ensuring proper data handling and user management.
This commit is contained in:
wizardchen
2026-05-24 21:38:05 +08:00
committed by lyingbug
parent e6ee87759d
commit 47a183aa65
43 changed files with 3322 additions and 146 deletions
+2 -12
View File
@@ -6,7 +6,7 @@ import { MessagePlugin, NotifyPlugin } from 'tdesign-vue-next'
import ManualKnowledgeEditor from '@/components/manual-knowledge-editor.vue'
import { useAuthStore } from '@/stores/auth'
import { useSettingsStore } from '@/stores/settings'
import { getCurrentUser } from '@/api/auth'
import { getCurrentUser, userInfoFromApi } from '@/api/auth'
import { consumePendingTenantSwitchToast } from '@/utils/tenantSwitch'
import { useRoleLabel } from '@/composables/useRoleLabel'
import { notifyLoginSuccess } from '@/utils/loginNotify'
@@ -52,17 +52,7 @@ const syncOIDCUserContext = async () => {
}
const { user, tenant, memberships } = currentUserResponse.data
authStore.setUser({
id: user.id || '',
username: user.username || '',
email: user.email || '',
avatar: user.avatar,
tenant_id: String(user.tenant_id || tenant?.id || ''),
can_access_all_tenants: user.can_access_all_tenants || false,
preferences: user.preferences,
created_at: user.created_at || new Date().toISOString(),
updated_at: user.updated_at || new Date().toISOString()
})
authStore.setUser(userInfoFromApi(user, tenant?.id))
if (tenant) {
authStore.setTenant({
id: String(tenant.id) || '',
+42
View File
@@ -19,6 +19,7 @@ export interface LoginResponse {
avatar?: string
tenant_id: number
can_access_all_tenants?: boolean
is_system_admin?: boolean
is_active: boolean
created_at: string
updated_at: string
@@ -97,10 +98,51 @@ export interface UserInfo {
tenant_id: string
can_access_all_tenants?: boolean
preferences?: UserPreferences
is_system_admin?: boolean
created_at: string
updated_at: string
}
/**
* 把后端返回的 user JSON 规范化成前端 UserInfo。
*
* 历史上有 4 处独立的 setUser 调用(Login、autoSetup、token rehydrate、
* /auth/me 主动 refresh)各自手写字段白名单,每加一个 user 字段都要在
* 4 处同步——否则该字段就被悄悄过滤掉。is_system_admin 上线时就因为
* 漏拷一处而看不到「系统管理」入口;这个工厂存在的目的就是杜绝同类
* 漏拷再发生。**新增 user 字段请只改这里**。
*
* fallbackTenantId 是 tenant_id 缺失时的兜底来源——
* - autoSetup 响应顶层有 tenant.id,但 user 对象上没有 tenant_id
* - /auth/me 偶发只返回 user 不带 tenant 时也走兜底
* 调用方按需传入;不传则保持空字符串(与历史行为一致)。
*
* 字段读取统一走 `=== true` 而不是 `|| false`,对偶发非 boolean
* 类型(后端某天传 1/0 或字符串)做严格收敛,避免把 truthy 字符串
* 误判为权限通过。
*/
export function userInfoFromApi(
u: any,
fallbackTenantId?: string | number | null,
): UserInfo {
const tid =
u?.tenant_id !== undefined && u?.tenant_id !== null && u.tenant_id !== ''
? u.tenant_id
: fallbackTenantId ?? ''
return {
id: u?.id || '',
username: u?.username || '',
email: u?.email || '',
avatar: u?.avatar,
tenant_id: String(tid) || '',
can_access_all_tenants: u?.can_access_all_tenants === true,
is_system_admin: u?.is_system_admin === true,
preferences: u?.preferences,
created_at: u?.created_at || new Date().toISOString(),
updated_at: u?.updated_at || new Date().toISOString(),
}
}
// 租户信息接口
export interface TenantInfo {
id: string
+146
View File
@@ -221,3 +221,149 @@ export interface StorageCheckResponse {
export function checkStorageEngine(req: StorageCheckRequest): Promise<{ data: StorageCheckResponse }> {
return post('/api/v1/system/storage-engine-check', req)
}
// ---- System Admin Management ----
export interface SystemAdminUser {
id: string
username: string
email: string
avatar?: string
is_active: boolean
is_system_admin: boolean
created_at: string
updated_at: string
}
export interface PromoteUserRequest {
user_id: string
}
export interface RevokeSystemAdminRequest {
user_id: string
}
export interface ListSystemAdminsResponse {
total: number
admins: SystemAdminUser[]
}
/**
* Promote a user to system administrator.
*
* Backend handler (system.go) returns the updated UserInfo directly as
* the response body — no {data: ...} wrapping. The shared axios
* interceptor in utils/request.ts unwraps response.data at the
* interceptor layer, so the resolved value here IS the UserInfo.
*
* The `as unknown as T` cast is the project-wide pattern for telling
* TS "trust me, the interceptor unwraps this" — see api/auth/index.ts
* for the same convention. A naked `Promise<T>` annotation would
* compile (sometimes — vue-tsc is inconsistent on AxiosResponse vs
* inline interface assignability) but is fragile.
*/
export async function promoteUserToSystemAdmin(userId: string): Promise<SystemAdminUser> {
const response = await post('/api/v1/system/admin/promote', { user_id: userId })
return response as unknown as SystemAdminUser
}
/**
* Revoke system administrator privileges from a user.
* Same wrapping convention as promoteUserToSystemAdmin.
*/
export async function revokeSystemAdmin(userId: string): Promise<SystemAdminUser> {
const response = await post('/api/v1/system/admin/revoke', { user_id: userId })
return response as unknown as SystemAdminUser
}
/**
* List all system administrators (paginated).
* Returns {total, admins[]} directly — no {data: ...} wrapping.
*/
export async function listSystemAdmins(
params?: { offset?: number; limit?: number },
): Promise<ListSystemAdminsResponse> {
// The shared `get` helper doesn't accept a config object, so we
// assemble the query string manually. Both params are optional;
// the server applies sane defaults (offset=0, limit=50, max=200).
const qs = new URLSearchParams()
if (params?.offset != null) qs.set('offset', String(params.offset))
if (params?.limit != null) qs.set('limit', String(params.limit))
const suffix = qs.toString() ? `?${qs.toString()}` : ''
const response = await get(`/api/v1/system/admin/list${suffix}`)
return response as unknown as ListSystemAdminsResponse
}
// ---- System Settings (P1) ----
/**
* SystemSettingItem mirrors types.SystemSetting on the backend, exactly
* as the JSON API serialises it (no `data: ...` wrapping; see
* utils/request.ts:97 — the axios interceptor unwraps response.data
* project-wide). New fields here MUST also be added to backend
* types/system_setting.go.
*
* `value` is typed as `unknown` because the underlying JSONB column can
* hold an int / string / bool depending on `value_type`. Callers narrow
* via the value_type field (`'int' | 'string' | 'bool'`).
*/
export interface SystemSettingItem {
id: number
key: string
/** Raw JSON value — narrow via value_type before rendering. */
value: unknown
value_type: 'int' | 'string' | 'bool' | 'string_list'
category: string
description: string
/** P3+ — currently always false. UI may surface a "redacted" state when true. */
is_secret: boolean
/** P3+ — currently always false. UI may show "needs restart to take effect" badge when true. */
requires_restart: boolean
last_modified_by: string
created_at: string
updated_at: string
/**
* Allowed values for `value` when this setting is constrained. Populated by
* the service from the in-code registry; absent/empty means "free-form".
* Frontend renders a t-select instead of t-input when this is non-empty.
*/
enum?: string[]
}
/**
* List every system setting row (system-scope, not tenant-scope).
* Backend returns the array directly; we cast through `unknown` to match
* the project-wide axios contract (see utils/request.ts:97).
*/
export async function listSystemSettings(): Promise<SystemSettingItem[]> {
const response = await get('/api/v1/system/admin/settings')
return response as unknown as SystemSettingItem[]
}
/**
* Fetch a single system setting by key. Throws (via the axios interceptor)
* if the key is unknown to the registry, or if the row is not yet persisted.
*/
export async function getSystemSetting(key: string): Promise<SystemSettingItem> {
const response = await get(`/api/v1/system/admin/settings/${encodeURIComponent(key)}`)
return response as unknown as SystemSettingItem
}
/**
* Persist a new value for `key`. The backend validates the value against
* the registry-declared value_type and rejects mismatches with 400; the
* error message is surfaced via err.message (see utils/request.ts:209).
*
* Successful updates emit an audit row (action=system.setting_changed)
* carrying old/new values for forensics.
*/
export async function updateSystemSetting(
key: string,
value: unknown,
): Promise<SystemSettingItem> {
const response = await put(
`/api/v1/system/admin/settings/${encodeURIComponent(key)}`,
{ value },
)
return response as unknown as SystemSettingItem
}
+32 -13
View File
@@ -110,6 +110,20 @@
<t-icon name="setting" class="menu-icon" />
<span>{{ $t('general.allSettings') }}</span>
</div>
<!--
System administration entry — visible only to users with the
platform-wide is_system_admin flag. Hidden for everyone else,
including tenant Owners. Real authorisation lives server-side
(RequireSystemAdmin middleware); this is UI gating only.
-->
<div
v-if="authStore.isSystemAdmin"
class="menu-item"
@click="handleSystemAdmin"
>
<t-icon name="server" class="menu-icon" />
<span>系统管理</span>
</div>
<!-- 切换租户入口在下拉「当前租户」区块 hover;此处仅为分隔线与菜单项。 -->
<div class="menu-divider"></div>
<div class="menu-item" @click="openClawhubSkill">
@@ -231,7 +245,7 @@ import { useRouter } from 'vue-router'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import { MessagePlugin } from 'tdesign-vue-next'
import { getCurrentUser, logout as logoutApi } from '@/api/auth'
import { getCurrentUser, logout as logoutApi, userInfoFromApi } from '@/api/auth'
import { useI18n } from 'vue-i18n'
import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue'
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
@@ -343,6 +357,15 @@ const handleSettings = () => {
router.push('/platform/settings')
}
// Open the platform-wide system administration area. Mirrors the
// existing handleSettings flow: dismiss the menu, then route. There is
// no UI store flag for system-admin (settings.vue uses one for its
// modal-overlay pattern; system area is a regular routed page).
const handleSystemAdmin = () => {
menuVisible.value = false
router.push('/platform/system')
}
// Hover-driven submenu controls. A small hide delay tolerates the pointer
// slipping off briefly onto the gap between menu item and submenu pane.
const showIMSubmenu = () => {
@@ -644,18 +667,14 @@ const loadUserInfo = async () => {
email: user.email || 'user@example.com',
avatar: user.avatar || ''
}
// 同时更新 authStore 中的用户信息,确保包含 can_access_all_tenants 字段
authStore.setUser({
id: user.id,
username: user.username,
email: user.email,
avatar: user.avatar,
tenant_id: user.tenant_id,
can_access_all_tenants: user.can_access_all_tenants || false,
preferences: user.preferences,
created_at: user.created_at,
updated_at: user.updated_at
})
// 同时更新 authStore 中的用户信息,确保包含 can_access_all_tenants /
// is_system_admin 等所有字段。MUST 走 userInfoFromApi 工厂——历史
// 上这里手写字段白名单,每加一个 user 字段都要在 5 个 setUser 调用
// 点同步,is_system_admin 就因为漏了这一处导致进入 platform 后
// user.value 的字段被 mount 时的 loadUserInfo 静默覆盖回 undefined
// (同时污染 localStorage),系统管理入口在 hover 工作空间触发
// refreshFromAuthMe 后才出现。新增字段请只改 userInfoFromApi。
authStore.setUser(userInfoFromApi(user))
// 如果返回了租户信息,也更新租户信息
if (response.data.tenant) {
authStore.setTenant({
+41 -23
View File
@@ -1,7 +1,7 @@
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { autoSetup, getCurrentUser } from '@/api/auth'
import { autoSetup, getCurrentUser, userInfoFromApi } from '@/api/auth'
/** Lite /桌面 WebView 硬刷新时可能只打开 `/`,用 session 记住上次页面以便恢复 */
const LITE_LAST_PATH_KEY = 'weknora_lite_last_path'
@@ -140,6 +140,33 @@ const router = createRouter({
component: () => import("../views/organization/OrganizationList.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
// System administration area — gated to users with
// user.is_system_admin === true. The route guard below honours
// the meta.requiresSystemAdmin flag; non-admins are bounced to
// /platform/knowledge-bases. Real authorisation lives server-side.
{
path: "system",
component: () => import("../views/system/SystemLayout.vue"),
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true },
redirect: "/platform/system/settings",
children: [
{
// P1 default landing page — the SystemAdmin lands here
// because most platform-level operations involve tweaking
// a setting, not promoting another admin.
path: "settings",
name: "systemSettings",
component: () => import("../views/system/SystemSettings.vue"),
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }
},
{
path: "admins",
name: "systemAdmins",
component: () => import("../views/system/SystemAdmins.vue"),
meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }
},
],
},
],
},
// Dev-only markdown rendering test page
@@ -155,17 +182,7 @@ const router = createRouter({
// 持久化 auto-setup / login 返回的认证信息到 store
function persistLoginResponse(authStore: ReturnType<typeof useAuthStore>, response: any) {
if (response.user && response.tenant && response.token) {
authStore.setUser({
id: response.user.id || '',
username: response.user.username || '',
email: response.user.email || '',
avatar: response.user.avatar,
tenant_id: String(response.tenant.id) || '',
can_access_all_tenants: response.user.can_access_all_tenants || false,
preferences: response.user.preferences,
created_at: response.user.created_at || new Date().toISOString(),
updated_at: response.user.updated_at || new Date().toISOString()
})
authStore.setUser(userInfoFromApi(response.user, response.tenant.id))
authStore.setToken(response.token)
if (response.refresh_token) {
authStore.setRefreshToken(response.refresh_token)
@@ -201,17 +218,7 @@ async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore
return false
}
authStore.setUser({
id: user.id || '',
username: user.username || '',
email: user.email || '',
avatar: user.avatar,
tenant_id: String(user.tenant_id || response.data?.tenant?.id || ''),
can_access_all_tenants: user.can_access_all_tenants || false,
preferences: user.preferences,
created_at: user.created_at || new Date().toISOString(),
updated_at: user.updated_at || new Date().toISOString(),
})
authStore.setUser(userInfoFromApi(user, response.data?.tenant?.id))
const tenant = response.data?.tenant
if (tenant) {
@@ -315,6 +322,17 @@ router.beforeEach(async (to, from, next) => {
}
}
// SystemAdmin gate — checked AFTER auth so a non-admin who's logged
// out gets redirected to /login first (consistent with how the rest
// of the auth flow works), and only an authenticated non-admin sees
// the bounce. This is UI-only; the server enforces the real check.
if (to.meta.requiresSystemAdmin === true) {
if (!authStore.isSystemAdmin) {
next('/platform/knowledge-bases')
return
}
}
next()
})
+24 -12
View File
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, TenantInfo, KnowledgeBaseInfo } from '@/api/auth'
import { userInfoFromApi } from '@/api/auth'
import type { TenantInfo as TenantInfoFromAPI } from '@/api/tenant'
import i18n from '@/i18n'
import { reloadFontFromStorage } from '@/composables/useFont'
@@ -87,6 +88,22 @@ export const useAuthStore = defineStore('auth', () => {
return user.value?.can_access_all_tenants || false
})
// isSystemAdmin reflects the platform-wide system-administrator flag
// (User.IsSystemAdmin on the server). It is independent of per-tenant
// Owner/Admin/Contributor/Viewer roles — a system admin can manage
// global settings, built-in models, and other system admins regardless
// of which tenant they're currently scoped into.
//
// SECURITY: same caveat as currentTenantRole — this value is hydrated
// from localStorage on reload and is therefore tamper-prone client-side.
// Use it ONLY to gate UI visibility (menu entries, route guards). All
// real authorisation lives in the server-side RequireSystemAdmin
// middleware (see internal/middleware/rbac.go). A user who flips this
// bit in DevTools will get a 403 the moment they hit a guarded endpoint.
const isSystemAdmin = computed(() => {
return user.value?.is_system_admin === true
})
// currentTenantRole returns the user's role in the active tenant
// (defaulting to '' when memberships have not been loaded). Used by
// role-aware UI gating; PR 2 wires backend enforcement, PR 3 uses
@@ -307,17 +324,7 @@ export const useAuthStore = defineStore('auth', () => {
const u = response.data?.user
if (!response.success || !u) return false
setUser({
id: u.id || '',
username: u.username || '',
email: u.email || '',
avatar: u.avatar,
tenant_id: String(u.tenant_id || response.data?.tenant?.id || ''),
can_access_all_tenants: u.can_access_all_tenants || false,
preferences: u.preferences,
created_at: u.created_at || new Date().toISOString(),
updated_at: u.updated_at || new Date().toISOString(),
})
setUser(userInfoFromApi(u, response.data?.tenant?.id))
const tenantSnapshot = response.data?.tenant
if (tenantSnapshot) {
@@ -407,7 +414,11 @@ export const useAuthStore = defineStore('auth', () => {
if (storedUser) {
try {
user.value = JSON.parse(storedUser)
// 走 userInfoFromApi 把老 localStorage(可能缺新字段,如
// is_system_admin)规范化一遍,避免「我新加了字段、但老登录态
// 没经过登录响应处理过、字段就永远是 undefined」的死角。
// 这是「漏拷 4 处」之外的第 5 个隐藏入口,专门给页面刷新走的。
user.value = userInfoFromApi(JSON.parse(storedUser))
} catch (e) {
console.error(i18n.global.t('authStore.errors.parseUserFailed'), e)
}
@@ -498,6 +509,7 @@ export const useAuthStore = defineStore('auth', () => {
currentTenantName,
currentUserId,
canAccessAllTenants,
isSystemAdmin,
currentTenantRole,
hasRole,
effectiveTenantId,
+2 -12
View File
@@ -379,7 +379,7 @@ import { Autoplay, EffectFade, Pagination } from 'swiper/modules'
import 'swiper/css'
import 'swiper/css/effect-fade'
import 'swiper/css/pagination'
import { login, register, getOIDCAuthorizationURL, getOIDCConfig, autoSetup, getAuthConfig } from '@/api/auth'
import { login, register, getOIDCAuthorizationURL, getOIDCConfig, autoSetup, getAuthConfig, userInfoFromApi } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import { useI18n } from 'vue-i18n'
@@ -562,17 +562,7 @@ const persistLoginResponse = async (response: any) => {
// server honoured a remembered last-active-tenant preference) is
// expressed separately via setSelectedTenant below.
const homeTenantIdRaw = response.user.tenant_id ?? activeTenant.id
authStore.setUser({
id: response.user.id || '',
username: response.user.username || '',
email: response.user.email || '',
avatar: response.user.avatar,
tenant_id: String(homeTenantIdRaw) || '',
can_access_all_tenants: response.user.can_access_all_tenants || false,
preferences: response.user.preferences,
created_at: response.user.created_at || new Date().toISOString(),
updated_at: response.user.updated_at || new Date().toISOString()
})
authStore.setUser(userInfoFromApi(response.user, homeTenantIdRaw))
authStore.setToken(response.token)
if (response.refresh_token) {
authStore.setRefreshToken(response.refresh_token)
+259
View File
@@ -0,0 +1,259 @@
<template>
<!--
SystemAdmins — list & manage the platform-wide system administrators.
Grants/revokes via the /api/v1/system/admin/{promote,revoke,list}
endpoints (server-side guarded by RequireSystemAdmin middleware).
P0 milestone scope is deliberately minimal:
- Paginated list of current system admins
- Promote a user by email
- Revoke an existing admin (with last-admin & self-revoke server guards)
Future milestones can layer richer UX on top — search, audit-log
drawer, bulk operations — but the API surface and gating are stable.
-->
<div class="system-admins">
<div class="page-header">
<div>
<h1 class="page-title">系统管理员</h1>
<p class="page-desc">
系统管理员独立于租户角色,拥有平台级管理权限(管理其他系统管理员、全局设置、内置模型等)。
</p>
</div>
<t-button theme="primary" @click="openPromoteDialog">
<template #icon><t-icon name="add" /></template>
提升用户为系统管理员
</t-button>
</div>
<t-card class="admins-card" :bordered="false">
<t-table
row-key="id"
:data="admins"
:columns="columns"
:loading="loading"
size="medium"
hover
stripe
>
<template #status="{ row }">
<t-tag v-if="row.is_active" theme="success" variant="light">
活跃
</t-tag>
<t-tag v-else theme="warning" variant="light">已停用</t-tag>
</template>
<template #actions="{ row }">
<t-button
theme="danger"
variant="text"
size="small"
:disabled="row.id === currentUserId"
@click="confirmRevoke(row)"
>
撤销权限
</t-button>
</template>
</t-table>
<div class="pagination-bar" v-if="total > 0">
<t-pagination
v-model="page"
v-model:page-size="pageSize"
:total="total"
:page-size-options="[20, 50, 100]"
@change="loadAdmins"
/>
</div>
</t-card>
<!-- Promote dialog -->
<t-dialog
v-model:visible="promoteDialogVisible"
header="提升用户为系统管理员"
:confirm-btn="{ content: '确认提升', loading: promoting }"
@confirm="submitPromote"
@close="resetPromoteDialog"
>
<p class="dialog-hint">
请输入要提升的用户的 ID。该用户必须已经在系统中注册过;操作幂等,已是管理员的用户不会被重复提升。
</p>
<t-input
v-model="promoteUserId"
placeholder="用户 ID(UUID 形式)"
:disabled="promoting"
clearable
/>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
import {
listSystemAdmins,
promoteUserToSystemAdmin,
revokeSystemAdmin,
type SystemAdminUser,
} from '@/api/system'
const authStore = useAuthStore()
const currentUserId = computed(() => authStore.currentUserId)
const admins = ref<SystemAdminUser[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const promoteDialogVisible = ref(false)
const promoteUserId = ref('')
const promoting = ref(false)
// Columns are defined as a computed (vs a static const) so future
// localization/translation can hook in without component refactor.
const columns = [
{ colKey: 'username', title: '用户名', width: 180 },
{ colKey: 'email', title: '邮箱', width: 280 },
{ colKey: 'status', title: '状态', width: 100 },
{ colKey: 'created_at', title: '注册时间', width: 200 },
{ colKey: 'actions', title: '操作', width: 120, align: 'right' as const },
]
async function loadAdmins() {
loading.value = true
try {
const offset = (page.value - 1) * pageSize.value
// listSystemAdmins resolves to ListSystemAdminsResponse directly —
// utils/request.ts already unwraps axios's response.data wrapper at
// the interceptor layer (see line 97), so an extra `.data` here
// would explode at runtime as "Cannot read property 'admins' of
// undefined" and surface as the generic load-failed toast.
const res = await listSystemAdmins({ offset, limit: pageSize.value })
admins.value = res.admins ?? []
total.value = res.total ?? 0
} catch (err) {
// Surface a toast and bail — keeping prior list so the user isn't
// left staring at an empty table on a transient failure.
MessagePlugin.error('加载系统管理员列表失败')
console.error('listSystemAdmins failed:', err)
} finally {
loading.value = false
}
}
function openPromoteDialog() {
promoteUserId.value = ''
promoteDialogVisible.value = true
}
function resetPromoteDialog() {
promoteUserId.value = ''
promoting.value = false
}
async function submitPromote() {
const uid = promoteUserId.value.trim()
if (!uid) {
MessagePlugin.warning('请输入用户 ID')
return
}
promoting.value = true
try {
await promoteUserToSystemAdmin(uid)
MessagePlugin.success('已提升为系统管理员')
promoteDialogVisible.value = false
await loadAdmins()
} catch (err: any) {
// utils/request.ts 把后端的 {error: "..."} 提升到了顶层 message
// 字段(line 197-213),同时保留原始 data 字段。我们优先读 message
// —— 它已经是后端的 human-readable 错误文案,覆盖了 user-not-found
// / 自我撤销等业务错误场景。
const msg = err?.message || err?.error || '提升失败,请检查用户 ID 后重试'
MessagePlugin.error(msg)
} finally {
promoting.value = false
}
}
function confirmRevoke(row: SystemAdminUser) {
// Confirmation dialog is mandatory — revoking is destructive and
// the server's last-admin / self-revoke guards return 400 with a
// human-readable message which we re-surface in submitRevoke.
const confirmDialog = DialogPlugin.confirm({
header: '撤销系统管理员权限',
body: `确定要撤销用户 "${row.username}" (${row.email}) 的系统管理员权限吗?`,
confirmBtn: { content: '确认撤销', theme: 'danger' },
cancelBtn: '取消',
onConfirm: async () => {
await submitRevoke(row.id)
confirmDialog.destroy()
},
onClose: () => confirmDialog.destroy(),
})
}
async function submitRevoke(userId: string) {
try {
await revokeSystemAdmin(userId)
MessagePlugin.success('已撤销系统管理员权限')
await loadAdmins()
} catch (err: any) {
// 同 submitPromote 的注释 —— 后端 last-admin / self-revoke 保护
// 走 400 + {error: "..."},被拦截器抬到 err.message。
const msg = err?.message || err?.error || '撤销失败'
MessagePlugin.error(msg)
}
}
onMounted(() => {
loadAdmins()
})
</script>
<style scoped>
.system-admins {
max-width: 1100px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
margin-bottom: 20px;
}
.page-title {
margin: 0 0 6px;
font-size: 22px;
font-weight: 600;
color: var(--td-text-color-primary, #000);
}
.page-desc {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: var(--td-text-color-secondary, #666);
max-width: 720px;
}
.admins-card {
margin-top: 8px;
}
.pagination-bar {
margin-top: 16px;
display: flex;
justify-content: flex-end;
}
.dialog-hint {
margin: 0 0 12px;
font-size: 13px;
color: var(--td-text-color-secondary, #666);
line-height: 1.6;
}
</style>
+129
View File
@@ -0,0 +1,129 @@
<template>
<!--
SystemLayout — top-level shell for the platform-wide administration
area (/platform/system/*). Gated by meta.requiresSystemAdmin in the
router; reaching this component means the caller is an authenticated
SystemAdmin.
Sidebar is intentionally simple for the P0 milestone: only the
"Administrators" page is wired. Future P1+ pages (global settings,
built-in models, audit log, tenants overview) plug in here as new
sidebar items + child routes.
-->
<div class="system-layout">
<aside class="system-sidebar">
<div class="system-sidebar-header">
<h2 class="system-sidebar-title">系统管理</h2>
<div class="system-sidebar-subtitle">SystemAdmin</div>
</div>
<nav class="system-nav">
<router-link
v-for="item in navItems"
:key="item.name"
:to="{ name: item.name }"
v-slot="{ isActive, navigate }"
custom
>
<div
:class="['system-nav-item', { active: isActive }]"
@click="navigate"
>
<t-icon :name="item.icon" class="system-nav-icon" />
<span class="system-nav-label">{{ item.label }}</span>
</div>
</router-link>
</nav>
</aside>
<main class="system-content">
<router-view />
</main>
</div>
</template>
<script setup lang="ts">
// Nav items are declared here (not in a separate config file) because
// the list is short and tightly coupled to which child routes exist.
// When a new child route is added in router/index.ts under /platform/system,
// add a matching entry here.
const navItems = [
{ name: 'systemSettings', label: '全局设置', icon: 'setting' },
{ name: 'systemAdmins', label: '系统管理员', icon: 'user-shield' },
]
</script>
<style scoped>
.system-layout {
display: flex;
height: 100%;
width: 100%;
background: var(--td-bg-color-page, #f5f5f5);
}
.system-sidebar {
width: 240px;
flex-shrink: 0;
background: var(--td-bg-color-container, #fff);
border-right: 1px solid var(--td-border-level-1-color, #e7e7e7);
padding: 20px 12px;
display: flex;
flex-direction: column;
gap: 16px;
}
.system-sidebar-header {
padding: 0 12px 12px;
border-bottom: 1px solid var(--td-border-level-1-color, #e7e7e7);
}
.system-sidebar-title {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--td-text-color-primary, #000);
}
.system-sidebar-subtitle {
font-size: 11px;
color: var(--td-text-color-placeholder, #999);
margin-top: 4px;
letter-spacing: 0.5px;
}
.system-nav {
display: flex;
flex-direction: column;
gap: 2px;
}
.system-nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
color: var(--td-text-color-primary, #333);
transition: background-color 0.15s;
}
.system-nav-item:hover {
background: var(--td-bg-color-component-hover, #f3f3f3);
}
.system-nav-item.active {
background: var(--td-brand-color-light, #e0eaff);
color: var(--td-brand-color, #0052d9);
font-weight: 500;
}
.system-nav-icon {
font-size: 16px;
}
.system-content {
flex: 1;
overflow: auto;
padding: 24px 32px;
}
</style>
@@ -0,0 +1,475 @@
<template>
<!--
SystemSettings — platform-wide tunables (system_settings table) for
SystemAdmin. Gated server-side by RequireSystemAdmin middleware;
the route also has meta.requiresSystemAdmin so non-admins never
reach this component (see frontend/src/router/index.ts).
UI principle: each row is independently editable + savable. We don't
show a global "Save all" button because backend Update is per-key
(the audit log records each change individually) and the
"save-and-see-effect" loop is friendlier per-field. Validation is
client-side first (matching value_type), server-side strict.
-->
<div class="system-settings">
<div class="page-header">
<div>
<h1 class="page-title">全局设置</h1>
<p class="page-desc">
平台级运行时配置。修改保存后立即生效(不需要重启服务)。
所有变更会写入审计日志。
</p>
</div>
<t-button variant="text" @click="loadSettings" :loading="loading">
<template #icon><t-icon name="refresh" /></template>
刷新
</t-button>
</div>
<div v-if="loading && groupedSettings.length === 0" class="loading-state">
<t-loading text="加载中..." />
</div>
<div v-else-if="groupedSettings.length === 0" class="empty-state">
<t-icon name="info-circle" size="32px" />
<div>暂无可配置的系统设置</div>
</div>
<t-card
v-for="group in groupedSettings"
:key="group.category"
class="settings-group"
:bordered="false"
:header-bordered="true"
>
<template #title>
<div class="group-title">
<span class="group-title-text">{{ categoryLabel(group.category) }}</span>
<span class="group-title-count">{{ group.items.length }}</span>
</div>
</template>
<div
v-for="item in group.items"
:key="item.key"
class="setting-row"
>
<div class="setting-info">
<div class="setting-key">
<span class="setting-key-text">{{ item.key }}</span>
<t-tag
v-if="item.requires_restart"
theme="warning"
variant="light"
size="small"
>需重启</t-tag>
<t-tag
v-if="item.is_secret"
theme="primary"
variant="light"
size="small"
>敏感</t-tag>
</div>
<div v-if="item.description" class="setting-desc">{{ item.description }}</div>
<div class="setting-meta">
<span>类型: {{ item.value_type }}</span>
<span v-if="item.last_modified_by">· 最后修改: {{ item.last_modified_by.slice(0, 8) }}</span>
<span v-if="item.updated_at">· {{ formatDate(item.updated_at) }}</span>
</div>
</div>
<div class="setting-control">
<!--
Per-type input. value_type drives which control we render:
int → InputNumber
bool → Switch
string_list → TagInput (each entry as a tag)
string → InputNumber/Input/Select depending on enum
When `enum` is non-empty (regardless of declared type, but
only meaningful for string), we override to a Select.
-->
<t-select
v-if="hasEnum(item)"
v-model="editValues[item.key]"
:options="enumOptions(item)"
:disabled="savingKey === item.key"
class="setting-input"
/>
<t-input-number
v-else-if="item.value_type === 'int'"
v-model="editValues[item.key]"
:placeholder="String(item.value)"
:disabled="savingKey === item.key"
theme="normal"
:step="1"
:min="0"
class="setting-input"
/>
<t-switch
v-else-if="item.value_type === 'bool'"
v-model="editValues[item.key]"
:disabled="savingKey === item.key"
/>
<t-tag-input
v-else-if="item.value_type === 'string_list'"
v-model="editValues[item.key]"
:placeholder="emptyListPlaceholder"
:disabled="savingKey === item.key"
class="setting-input setting-input--wide"
clearable
/>
<t-input
v-else
v-model="editValues[item.key]"
:placeholder="String(item.value)"
:disabled="savingKey === item.key"
class="setting-input"
clearable
/>
<t-button
theme="primary"
size="small"
:loading="savingKey === item.key"
:disabled="!isDirty(item)"
@click="saveSetting(item)"
>
保存
</t-button>
</div>
</div>
</t-card>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import {
listSystemSettings,
updateSystemSetting,
type SystemSettingItem,
} from '@/api/system'
// Friendly Chinese labels per category. Falls back to the raw category
// string when a new one shows up that we haven't translated yet, which
// is the right behaviour: a missing translation should be visible, not
// silently empty.
const CATEGORY_LABELS: Record<string, string> = {
limits: '上限',
agent: 'Agent',
auth: '认证',
security: '安全',
storage: '存储',
general: '通用',
}
function categoryLabel(c: string): string {
return CATEGORY_LABELS[c] || c
}
// Keys that change platform-wide trust boundaries. Saving these triggers
// an extra "are you sure?" dialog so a careless click can't, say, flip
// auth.registration_mode=self_serve and let the public spam the system.
// New high-impact keys can be added here when they ship.
const HIGH_RISK_KEYS = new Set<string>([
'ssrf.whitelist',
'auth.registration_mode',
])
// Friendly labels for enum options (drives the t-select dropdown text).
// We keep them inline rather than fetching from i18n because (a) the
// list is small, (b) the options are tied to backend constants and
// shouldn't drift, (c) translators don't typically need to see them.
const ENUM_LABELS: Record<string, Record<string, string>> = {
'auth.registration_mode': {
self_serve: '自助注册(任何人可注册)',
invite_only: '仅邀请(关闭公网注册)',
},
}
const emptyListPlaceholder = '回车添加条目,例:example.com / *.foo.com / 10.0.0.0/8'
const settings = ref<SystemSettingItem[]>([])
const loading = ref(false)
const savingKey = ref<string | null>(null)
// Reactive map of in-progress edits, keyed by setting key. We don't
// mutate the canonical `settings` array directly so a failed save
// leaves the original value visible until the user retries or refreshes.
// Initialised lazily in loadSettings; setting.value is the JSON-decoded
// form (number / boolean / string / string[]).
const editValues = reactive<Record<string, unknown>>({})
const groupedSettings = computed(() => {
const buckets: Record<string, SystemSettingItem[]> = {}
for (const item of settings.value) {
const c = item.category || 'general'
if (!buckets[c]) buckets[c] = []
buckets[c].push(item)
}
return Object.keys(buckets)
.sort()
.map((category) => ({ category, items: buckets[category] }))
})
function hasEnum(item: SystemSettingItem): boolean {
return Array.isArray(item.enum) && item.enum.length > 0
}
function enumOptions(item: SystemSettingItem): { label: string; value: string }[] {
const opts = item.enum ?? []
const labelMap = ENUM_LABELS[item.key] ?? {}
return opts.map((v) => ({ label: labelMap[v] ?? v, value: v }))
}
// isDirty drives the Save button's disabled state. Arrays need
// element-wise comparison; primitives use strict equality. We don't
// import a lodash isEqual to keep the bundle small — the comparison
// surface is intentionally narrow (4 value_types).
function isDirty(item: SystemSettingItem): boolean {
const cur = editValues[item.key]
const orig = item.value
if (Array.isArray(cur) && Array.isArray(orig)) {
if (cur.length !== orig.length) return true
for (let i = 0; i < cur.length; i++) {
if (cur[i] !== orig[i]) return true
}
return false
}
return cur !== orig
}
function formatDate(isoString: string): string {
try {
const d = new Date(isoString)
return d.toLocaleString('zh-CN', { hour12: false })
} catch {
return isoString
}
}
async function loadSettings() {
loading.value = true
try {
const list = await listSystemSettings()
settings.value = list
// Reset edit values to the canonical state on every load — no
// partial drafts survive a refresh, which avoids the "I came back
// and my unsaved edits look saved" trap.
for (const item of list) {
// Defensive copy for arrays so the t-tag-input doesn't mutate
// the canonical settings entry through the v-model binding.
editValues[item.key] = Array.isArray(item.value)
? [...(item.value as unknown[])]
: item.value
}
} catch (err: any) {
const msg = err?.message || '加载系统设置失败'
MessagePlugin.error(msg)
} finally {
loading.value = false
}
}
async function saveSetting(item: SystemSettingItem) {
if (!isDirty(item)) return // double-click guard
// High-risk keys get an extra confirmation. The dialog text is
// intentionally specific: a generic "are you sure?" trains people to
// click through. Mention the actual setting + new value so the user
// re-reads what they're about to do.
if (HIGH_RISK_KEYS.has(item.key)) {
const confirmed = await new Promise<boolean>((resolve) => {
const dlg = DialogPlugin.confirm({
header: '高危操作确认',
body: highRiskConfirmBody(item),
confirmBtn: { content: '确认保存', theme: 'danger' },
cancelBtn: '取消',
onConfirm: () => {
resolve(true)
dlg.destroy()
},
onClose: () => {
resolve(false)
dlg.destroy()
},
})
})
if (!confirmed) return
}
await persistSetting(item)
}
function highRiskConfirmBody(item: SystemSettingItem): string {
const newValue = editValues[item.key]
const renderedValue = Array.isArray(newValue)
? newValue.length === 0
? '(空)'
: newValue.join(', ')
: String(newValue)
switch (item.key) {
case 'auth.registration_mode':
return `即将把「自助注册模式」改为:${renderedValue}\n\n` +
`如果切到 self_serve,公网任何人都可以注册账号 — 务必确认是预期行为。`
case 'ssrf.whitelist':
return `即将把 SSRF 白名单改为:${renderedValue}\n\n` +
`白名单中的主机/IP/网段会绕过 SSRF 防护。错误配置可能让 Agent 访问内网服务。`
default:
return `即将把「${item.key}」改为:${renderedValue}`
}
}
async function persistSetting(item: SystemSettingItem) {
const newValue = editValues[item.key]
savingKey.value = item.key
try {
const updated = await updateSystemSetting(item.key, newValue)
// Replace the row in-place so the table stays at scroll position
// and other rows' edit state isn't disturbed.
const idx = settings.value.findIndex((s) => s.key === item.key)
if (idx >= 0) {
settings.value[idx] = updated
}
editValues[item.key] = Array.isArray(updated.value)
? [...(updated.value as unknown[])]
: updated.value
MessagePlugin.success(`已保存 ${item.key}`)
} catch (err: any) {
const msg = err?.message || '保存失败'
MessagePlugin.error(msg)
} finally {
savingKey.value = null
}
}
onMounted(() => {
loadSettings()
})
</script>
<style scoped>
.system-settings {
max-width: 980px;
}
.page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
margin-bottom: 20px;
}
.page-title {
margin: 0 0 6px;
font-size: 22px;
font-weight: 600;
color: var(--td-text-color-primary, #000);
}
.page-desc {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: var(--td-text-color-secondary, #666);
max-width: 720px;
}
.loading-state,
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 60px 0;
color: var(--td-text-color-placeholder, #999);
}
.settings-group {
margin-bottom: 16px;
}
.group-title {
display: flex;
align-items: center;
gap: 8px;
}
.group-title-text {
font-size: 15px;
font-weight: 600;
}
.group-title-count {
font-size: 12px;
color: var(--td-text-color-placeholder, #999);
background: var(--td-bg-color-component, #f5f5f5);
padding: 1px 8px;
border-radius: 10px;
}
.setting-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
padding: 14px 0;
border-bottom: 1px solid var(--td-border-level-1-color, #eee);
}
.setting-row:last-child {
border-bottom: none;
padding-bottom: 0;
}
.setting-info {
flex: 1;
min-width: 0;
}
.setting-key {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 4px;
}
.setting-key-text {
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary, #000);
font-family: var(--td-font-family-mono, monospace);
}
.setting-desc {
font-size: 13px;
line-height: 1.6;
color: var(--td-text-color-secondary, #666);
margin-bottom: 4px;
}
.setting-meta {
font-size: 11px;
color: var(--td-text-color-placeholder, #999);
display: flex;
gap: 4px;
flex-wrap: wrap;
}
.setting-control {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
.setting-input {
width: 220px;
}
.setting-input--wide {
width: 420px;
}
</style>