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
+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
}