feat: 用户与权限管理
新增 PermissionCode 权限类型与用户/权限 API,路由注册用户设置/创建/权限页与无权访问页并接入权限守卫,AppSidebar 按权限过滤菜单并新增用户设置入口,auth store 与 mock 适配器同步支持用户管理与新登录认证,回归脚本与 npm 脚本注册。
This commit is contained in:
@@ -9,6 +9,7 @@
|
||||
"preview": "vite preview",
|
||||
"type-check": "vue-tsc -b --noEmit",
|
||||
"test": "node scripts/run-regressions.mjs",
|
||||
"test:login-layout": "node scripts/regression-login-layout.mjs",
|
||||
"test:default-dashboard": "node scripts/regression-default-dashboard.mjs",
|
||||
"test:dashboard": "node scripts/regression-dashboard.mjs",
|
||||
"test:data-process-list": "node scripts/regression-data-process-list.mjs",
|
||||
@@ -21,6 +22,7 @@
|
||||
"test:eval-detail": "node scripts/regression-eval-detail.mjs",
|
||||
"test:model-manage": "node scripts/regression-model-manage.mjs",
|
||||
"test:hardware": "node scripts/regression-hardware-dashboard.mjs",
|
||||
"test:user-settings": "node scripts/regression-user-settings.mjs",
|
||||
"test:training-log-layout": "node scripts/regression-training-log-layout.mjs",
|
||||
"test:fine-tune-create": "node scripts/regression-fine-tune-create-ui.mjs",
|
||||
"test:page-surface": "node scripts/regression-page-surface.mjs"
|
||||
|
||||
@@ -76,6 +76,7 @@ const selfSurfaceRoutes = [
|
||||
'data-process',
|
||||
'data-process/create',
|
||||
'dataset',
|
||||
'user-settings',
|
||||
]
|
||||
for (const routePath of selfSurfaceRoutes) {
|
||||
const routeBlock = extractRouteBlock(routerSource, routePath)
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { get, post } from '../request'
|
||||
import type { SystemInfo, HealthMetrics } from '@/types'
|
||||
import { del, get, post, put } from '../request'
|
||||
import type {
|
||||
CreateUserPayload,
|
||||
HealthMetrics,
|
||||
LoginResponse,
|
||||
SystemInfo,
|
||||
SystemUser,
|
||||
UpdateUserAccessPayload,
|
||||
} from '@/types'
|
||||
|
||||
/** 系统信息(CPU/内存/磁盘/GPU/网络/系统) */
|
||||
export const getSystemInfo = () => get<SystemInfo>('/system-info')
|
||||
@@ -9,4 +16,21 @@ export const getHealth = () => get<HealthMetrics>('/health')
|
||||
|
||||
/** 登录 */
|
||||
export const login = (username: string, password: string) =>
|
||||
post('/login', { username, password })
|
||||
post<LoginResponse>('/login', { username, password })
|
||||
|
||||
/** 用户列表 */
|
||||
export const getUsers = () => get<SystemUser[]>('/users')
|
||||
|
||||
/** 创建用户 */
|
||||
export const createUser = (payload: CreateUserPayload) =>
|
||||
post<SystemUser>('/users', payload)
|
||||
|
||||
/** 删除用户,currentUsername 用于防止删除当前登录账号 */
|
||||
export const deleteUser = (id: string, currentUsername: string) =>
|
||||
del<{ deleted: string }>(`/users/${encodeURIComponent(id)}`, {
|
||||
current_username: currentUsername,
|
||||
})
|
||||
|
||||
/** 更新用户角色、状态及页面权限 */
|
||||
export const updateUserAccess = (id: string, payload: UpdateUserAccessPayload) =>
|
||||
put<SystemUser>(`/users/${encodeURIComponent(id)}`, payload)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import type { PermissionCode } from '@/types'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -27,41 +28,65 @@ const activeMenu = computed(() => {
|
||||
return seg
|
||||
})
|
||||
|
||||
const menuGroups = [
|
||||
interface MenuItem {
|
||||
key: string
|
||||
label: string
|
||||
icon: string
|
||||
to: string
|
||||
permission: PermissionCode
|
||||
}
|
||||
|
||||
interface MenuGroup {
|
||||
title?: string
|
||||
showTitle?: boolean
|
||||
items: MenuItem[]
|
||||
}
|
||||
|
||||
const menuGroups: MenuGroup[] = [
|
||||
{
|
||||
// 服务看板:独立入口,不显示分类小标题
|
||||
showTitle: false,
|
||||
items: [{ key: 'dashboard', label: '服务看板', icon: 'fa-tachometer', to: '/dashboard' }],
|
||||
items: [{ key: 'dashboard', label: '服务看板', icon: 'fa-tachometer', to: '/dashboard', permission: 'dashboard' }],
|
||||
},
|
||||
{
|
||||
title: '模型服务',
|
||||
items: [
|
||||
{ key: 'fine-tune', label: '模型训练', icon: 'fa-cogs', to: '/fine-tune' },
|
||||
{ key: 'model-eval', label: '模型评测', icon: 'fa-line-chart', to: '/model-eval' },
|
||||
{ key: 'model-inference', label: '模型推理', icon: 'fa-server', to: '/model-inference' },
|
||||
{ key: 'model-manage', label: '模型管理', icon: 'fa-cube', to: '/model-manage' },
|
||||
{ key: 'fine-tune', label: '模型训练', icon: 'fa-cogs', to: '/fine-tune', permission: 'fine-tune' },
|
||||
{ key: 'model-eval', label: '模型评测', icon: 'fa-line-chart', to: '/model-eval', permission: 'model-eval' },
|
||||
{ key: 'model-inference', label: '模型推理', icon: 'fa-server', to: '/model-inference', permission: 'model-inference' },
|
||||
{ key: 'model-manage', label: '模型管理', icon: 'fa-cube', to: '/model-manage', permission: 'model-manage' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: '数据治理',
|
||||
items: [
|
||||
{ key: 'dataset', label: '数据集管理', icon: 'fa-file-text', to: '/dataset' },
|
||||
{ key: 'data-process', label: '数据处理', icon: 'fa-filter', to: '/data-process' },
|
||||
{ key: 'dataset', label: '数据集管理', icon: 'fa-file-text', to: '/dataset', permission: 'dataset' },
|
||||
{ key: 'data-process', label: '数据处理', icon: 'fa-filter', to: '/data-process', permission: 'data-process' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: '其他工具',
|
||||
items: [{ key: 'data-convert', label: '数据类型转换', icon: 'fa-exchange', to: '/data-convert' }],
|
||||
items: [{ key: 'data-convert', label: '数据类型转换', icon: 'fa-exchange', to: '/data-convert', permission: 'data-convert' }],
|
||||
},
|
||||
{
|
||||
title: '系统设置',
|
||||
items: [
|
||||
{ key: 'hardware', label: '平台性能', icon: 'fa-bar-chart', to: '/hardware' },
|
||||
{ key: 'logs', label: '查看日志', icon: 'fa-file-text', to: '/logs' },
|
||||
{ key: 'user-settings', label: '用户设置', icon: 'fa-users', to: '/user-settings', permission: 'user-settings' },
|
||||
{ key: 'hardware', label: '平台性能', icon: 'fa-bar-chart', to: '/hardware', permission: 'hardware' },
|
||||
{ key: 'logs', label: '查看日志', icon: 'fa-file-text', to: '/logs', permission: 'logs' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const visibleMenuGroups = computed(() =>
|
||||
menuGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
items: group.items.filter((item) => auth.hasPermission(item.permission)),
|
||||
}))
|
||||
.filter((group) => group.items.length > 0),
|
||||
)
|
||||
|
||||
/**
|
||||
* 传给 el-menu 的激活值。
|
||||
*
|
||||
@@ -78,7 +103,7 @@ watch(activeMenu, (value) => {
|
||||
})
|
||||
|
||||
async function handleSelect(key: string) {
|
||||
const all = menuGroups.flatMap((g) => g.items)
|
||||
const all = visibleMenuGroups.value.flatMap((g) => g.items)
|
||||
const target = all.find((i) => i.key === key)
|
||||
if (!target) return
|
||||
|
||||
@@ -115,7 +140,7 @@ function handleLogout() {
|
||||
active-text-color="var(--sidebar-active-text)"
|
||||
@select="handleSelect"
|
||||
>
|
||||
<template v-for="group in menuGroups" :key="group.title || group.items[0].key">
|
||||
<template v-for="group in visibleMenuGroups" :key="group.title || group.items[0].key">
|
||||
<div v-if="group.title" class="sidebar-section-title">{{ group.title }}</div>
|
||||
<el-menu-item
|
||||
v-for="item in group.items"
|
||||
@@ -134,8 +159,8 @@ function handleLogout() {
|
||||
<div class="footer-user" v-if="auth.username">
|
||||
<el-avatar :size="36" src="https://picsum.photos/id/1005/36/36" class="user-avatar" />
|
||||
<div class="user-info">
|
||||
<span class="user-name">{{ auth.username }}</span>
|
||||
<span class="user-role">Administrator</span>
|
||||
<span class="user-name">{{ auth.displayName }}</span>
|
||||
<span class="user-role">{{ auth.roleLabel }}</span>
|
||||
</div>
|
||||
<el-tooltip content="退出登录" placement="top">
|
||||
<div class="logout-btn" @click="handleLogout">
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
*/
|
||||
import type { AxiosAdapter, AxiosInstance, AxiosRequestConfig } from 'axios'
|
||||
import {
|
||||
mockLoginOk,
|
||||
mockHealth,
|
||||
mockSystemInfo,
|
||||
mockModels,
|
||||
@@ -33,6 +32,14 @@ import {
|
||||
normalizeDatasetVersionState,
|
||||
} from './datasetVersions'
|
||||
import type { StoredDatasetVersion, StoredDatasetVersionState } from './datasetVersions'
|
||||
import {
|
||||
authenticateMockUser,
|
||||
createMockUser,
|
||||
deleteMockUser,
|
||||
listMockUsers,
|
||||
updateMockUserAccess,
|
||||
UserMutationError,
|
||||
} from './users'
|
||||
|
||||
/** 模拟网络延迟 */
|
||||
function delay(ms = 200): Promise<void> {
|
||||
@@ -128,10 +135,12 @@ async function handleMock(config: AxiosRequestConfig) {
|
||||
|
||||
// ==================== 认证 ====================
|
||||
if (url === '/login' && method === 'post') {
|
||||
if (body.username === 'admin' && body.password === 'admin') {
|
||||
return ok(mockLoginOk.data)
|
||||
try {
|
||||
return ok(authenticateMockUser(String(body.username || ''), String(body.password || '')))
|
||||
} catch (error) {
|
||||
if (error instanceof UserMutationError) return fail(error.message, error.status)
|
||||
return fail('登录失败', 500)
|
||||
}
|
||||
return fail('账号或密码错误', 401)
|
||||
}
|
||||
if (url === '/web-log' && method === 'post') {
|
||||
return ok({ received: true })
|
||||
@@ -141,6 +150,37 @@ async function handleMock(config: AxiosRequestConfig) {
|
||||
if (url === '/health' && method === 'get') return ok(mockHealth)
|
||||
if (url === '/system-info' && method === 'get') return ok(mockSystemInfo)
|
||||
|
||||
// ==================== 用户设置 ====================
|
||||
if (url === '/users' && method === 'get') return ok(listMockUsers())
|
||||
if (url === '/users' && method === 'post') {
|
||||
try {
|
||||
return ok(createMockUser(body))
|
||||
} catch (error) {
|
||||
if (error instanceof UserMutationError) return fail(error.message, error.status)
|
||||
return fail('创建用户失败', 500)
|
||||
}
|
||||
}
|
||||
let userMatch = url.match(/^\/users\/([^/]+)$/)
|
||||
if (userMatch && method === 'put') {
|
||||
try {
|
||||
return ok(updateMockUserAccess(decodeURIComponent(userMatch[1]), body))
|
||||
} catch (error) {
|
||||
if (error instanceof UserMutationError) return fail(error.message, error.status)
|
||||
return fail('更新用户失败', 500)
|
||||
}
|
||||
}
|
||||
if (userMatch && method === 'delete') {
|
||||
try {
|
||||
return ok(deleteMockUser(
|
||||
decodeURIComponent(userMatch[1]),
|
||||
String(params.current_username || ''),
|
||||
))
|
||||
} catch (error) {
|
||||
if (error instanceof UserMutationError) return fail(error.message, error.status)
|
||||
return fail('删除用户失败', 500)
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 模型管理 ====================
|
||||
if (url === '/model-manage' && method === 'get') return ok(mockModels)
|
||||
if (url === '/model-manage/local-models' && method === 'get') return ok(mockLocalModels)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import type { PermissionCode } from '@/types'
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
@@ -191,6 +192,12 @@ const routes: RouteRecordRaw[] = [
|
||||
meta: { title: '数据类型转换' },
|
||||
},
|
||||
// 系统设置
|
||||
{
|
||||
path: 'permission-denied',
|
||||
name: 'permission-denied',
|
||||
component: () => import('@/views/system/PermissionDeniedView.vue'),
|
||||
meta: { title: '无权访问', skipPermission: true },
|
||||
},
|
||||
{
|
||||
path: 'hardware',
|
||||
name: 'hardware',
|
||||
@@ -203,6 +210,24 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import('@/views/system/LogsView.vue'),
|
||||
meta: { title: '查看日志' },
|
||||
},
|
||||
{
|
||||
path: 'user-settings',
|
||||
name: 'user-settings',
|
||||
component: () => import('@/views/system/UserSettingsView.vue'),
|
||||
meta: { title: '用户设置', pageSurface: 'self', permission: 'user-settings' },
|
||||
},
|
||||
{
|
||||
path: 'user-settings/create',
|
||||
name: 'user-create',
|
||||
component: () => import('@/views/system/UserCreateView.vue'),
|
||||
meta: { title: '创建用户', permission: 'user-settings' },
|
||||
},
|
||||
{
|
||||
path: 'user-settings/:id/permission',
|
||||
name: 'user-permission',
|
||||
component: () => import('@/views/system/UserPermissionView.vue'),
|
||||
meta: { title: '权限设置', permission: 'user-settings' },
|
||||
},
|
||||
{
|
||||
path: 'training-log/:id',
|
||||
name: 'training-log',
|
||||
@@ -222,6 +247,29 @@ const router = createRouter({
|
||||
routes,
|
||||
})
|
||||
|
||||
const permissionBySegment: Record<string, PermissionCode> = {
|
||||
dashboard: 'dashboard',
|
||||
'fine-tune': 'fine-tune',
|
||||
'training-log': 'fine-tune',
|
||||
'model-eval': 'model-eval',
|
||||
'model-inference': 'model-inference',
|
||||
'model-compare': 'model-inference',
|
||||
'model-manage': 'model-manage',
|
||||
dataset: 'dataset',
|
||||
'data-process': 'data-process',
|
||||
'data-convert': 'data-convert',
|
||||
tools: 'data-convert',
|
||||
hardware: 'hardware',
|
||||
logs: 'logs',
|
||||
'user-settings': 'user-settings',
|
||||
}
|
||||
|
||||
function requiredPermission(path: string, explicit?: unknown) {
|
||||
if (explicit) return explicit as PermissionCode
|
||||
const segment = path.split('/')[1]
|
||||
return permissionBySegment[segment]
|
||||
}
|
||||
|
||||
// 全局守卫:登录校验 + 会话超时
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const auth = useAuthStore()
|
||||
@@ -242,6 +290,14 @@ router.beforeEach((to, _from, next) => {
|
||||
return
|
||||
}
|
||||
|
||||
if (!to.meta.skipPermission) {
|
||||
const permission = requiredPermission(to.path, to.meta.permission)
|
||||
if (permission && !auth.hasPermission(permission)) {
|
||||
next({ name: 'permission-denied', replace: true })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 续期会话
|
||||
auth.refresh()
|
||||
next()
|
||||
|
||||
@@ -2,13 +2,63 @@ import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { login as loginApi } from '@/api/modules/system'
|
||||
import { SESSION_TIMEOUT } from '@/constants'
|
||||
import type { PermissionCode, SystemUser } from '@/types'
|
||||
|
||||
const USER_STORAGE_KEY = 'currentUser'
|
||||
|
||||
const allPermissions: PermissionCode[] = [
|
||||
'dashboard',
|
||||
'fine-tune',
|
||||
'model-eval',
|
||||
'model-inference',
|
||||
'model-manage',
|
||||
'dataset',
|
||||
'data-process',
|
||||
'data-convert',
|
||||
'hardware',
|
||||
'logs',
|
||||
'user-settings',
|
||||
]
|
||||
|
||||
function restoreUser(): SystemUser | null {
|
||||
const persisted = localStorage.getItem(USER_STORAGE_KEY)
|
||||
if (persisted) {
|
||||
try {
|
||||
return JSON.parse(persisted) as SystemUser
|
||||
} catch {
|
||||
localStorage.removeItem(USER_STORAGE_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
// 兼容改造前已经登录的 admin 会话。
|
||||
if (localStorage.getItem('username') === 'admin') {
|
||||
return {
|
||||
id: 'USR-0001',
|
||||
username: 'admin',
|
||||
display_name: '系统管理员',
|
||||
role: 'admin',
|
||||
status: 'active',
|
||||
permissions: allPermissions,
|
||||
create_time: '2026-01-01T08:00:00+08:00',
|
||||
protected: true,
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 认证 store
|
||||
* 沿用原项目 localStorage 的登录时间戳 + 5 分钟会话超时机制
|
||||
*/
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const username = ref<string>(localStorage.getItem('username') || '')
|
||||
const currentUser = ref<SystemUser | null>(restoreUser())
|
||||
const username = computed(() => currentUser.value?.username || '')
|
||||
const displayName = computed(() => currentUser.value?.display_name || username.value)
|
||||
const roleLabel = computed(() => {
|
||||
if (currentUser.value?.role === 'admin') return '超级管理员'
|
||||
if (currentUser.value?.role === 'operator') return '操作员'
|
||||
return '观察员'
|
||||
})
|
||||
const loginTime = ref<number>(parseInt(localStorage.getItem('loginTime') || '0', 10) || 0)
|
||||
|
||||
const isLoggedIn = computed(() => {
|
||||
@@ -18,13 +68,20 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
/** 登录 */
|
||||
async function login(user: string, password: string) {
|
||||
await loginApi(user, password)
|
||||
username.value = user
|
||||
const response = await loginApi(user, password)
|
||||
currentUser.value = response.user
|
||||
loginTime.value = Date.now()
|
||||
localStorage.setItem('username', user)
|
||||
localStorage.setItem('username', response.user.username)
|
||||
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(response.user))
|
||||
localStorage.setItem('loginTime', String(loginTime.value))
|
||||
}
|
||||
|
||||
/** 检查当前账号是否拥有指定模块权限。 */
|
||||
function hasPermission(permission?: PermissionCode) {
|
||||
if (!permission) return true
|
||||
return currentUser.value?.permissions.includes(permission) ?? false
|
||||
}
|
||||
|
||||
/** 续期会话(活跃时刷新) */
|
||||
function refresh() {
|
||||
if (isLoggedIn.value) {
|
||||
@@ -35,11 +92,23 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
/** 退出 */
|
||||
function logout() {
|
||||
username.value = ''
|
||||
currentUser.value = null
|
||||
loginTime.value = 0
|
||||
localStorage.removeItem('username')
|
||||
localStorage.removeItem(USER_STORAGE_KEY)
|
||||
localStorage.removeItem('loginTime')
|
||||
}
|
||||
|
||||
return { username, loginTime, isLoggedIn, login, refresh, logout }
|
||||
return {
|
||||
currentUser,
|
||||
username,
|
||||
displayName,
|
||||
roleLabel,
|
||||
loginTime,
|
||||
isLoggedIn,
|
||||
hasPermission,
|
||||
login,
|
||||
refresh,
|
||||
logout,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -383,6 +383,57 @@ export interface HealthMetrics {
|
||||
disk_percent?: number
|
||||
}
|
||||
|
||||
// ============ 用户与权限 ============
|
||||
/** 页面级权限编码,与路由模块保持一一对应 */
|
||||
export type PermissionCode =
|
||||
| 'dashboard'
|
||||
| 'fine-tune'
|
||||
| 'model-eval'
|
||||
| 'model-inference'
|
||||
| 'model-manage'
|
||||
| 'dataset'
|
||||
| 'data-process'
|
||||
| 'data-convert'
|
||||
| 'hardware'
|
||||
| 'logs'
|
||||
| 'user-settings'
|
||||
|
||||
export type UserRole = 'admin' | 'operator' | 'viewer'
|
||||
|
||||
export type UserStatus = 'active' | 'disabled'
|
||||
|
||||
export interface SystemUser {
|
||||
id: string
|
||||
username: string
|
||||
display_name: string
|
||||
role: UserRole
|
||||
status: UserStatus
|
||||
permissions: PermissionCode[]
|
||||
create_time: string
|
||||
last_login?: string
|
||||
protected?: boolean
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
token: string
|
||||
user: SystemUser
|
||||
}
|
||||
|
||||
export interface CreateUserPayload {
|
||||
username: string
|
||||
display_name: string
|
||||
password: string
|
||||
role: UserRole
|
||||
status?: UserStatus
|
||||
permissions?: PermissionCode[]
|
||||
}
|
||||
|
||||
export interface UpdateUserAccessPayload {
|
||||
role?: UserRole
|
||||
status?: UserStatus
|
||||
permissions?: PermissionCode[]
|
||||
}
|
||||
|
||||
// ============ 日志 ============
|
||||
export interface LogFile {
|
||||
file: string
|
||||
|
||||
Reference in New Issue
Block a user