feat: Console 查看页与自有查询端点(里程碑 4)

- 服务端 AuditQueryEndpoint(CustomEndpoint,group=audit.example.com):
  GET /apis/audit.example.com/v1alpha1/auditlogs/-/query
  - 等值筛选(fieldSelector 白名单)、关键字(resourceName/path contains OR)、
    结果(success 2xx-3xx / failure 4xx+)、时间区间(含边界 ISO-8601)
  - 全部走索引 Query + PageRequestImpl,无内存分页;页大小上限 100
- 风险项 #2 源码级证实并按预案落地:原生 fieldSelector 仅支持 =/!=/IN
- API 使用 2.22+ 新 Queries/Condition 体系(QueryFactory 已 @Deprecated)
- Console 页面:列表(VEntity 行:操作者/动作徽标/资源/路径/状态码/IP)+
  七维筛选栏 + 分页(10/20/50)+ 只读详情抽屉(完整字段 + 原始 JSON)
- 端点测试 10 例(默认值/筛选组合/参数校验/排序收敛),UI 类型检查通过
This commit is contained in:
2026-11-21 16:34:41 +08:00
parent 95b744f6f6
commit 5fa1660c5f
6 changed files with 1117 additions and 2 deletions
@@ -0,0 +1,414 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import {
VButton,
VCard,
VEmpty,
VEntity,
VEntityField,
VLoading,
VPageHeader,
VPagination,
VSpace,
VAlert,
IconRefreshLine,
} from '@halo-dev/components'
import type { AuditLog, ListResult } from '@/utils/audit'
import {
displayUsername,
formatTime,
isSuccessful,
localDateTimeToInstant,
methodBadgeClass,
} from '@/utils/audit'
import AuditLogDetail from './AuditLogDetail.vue'
/** 查询端点路径(与 AuditQueryEndpoint 保持一致)。 */
const QUERY_ENDPOINT =
'/apis/audit.example.com/v1alpha1/auditlogs/-/query'
const RESOURCE_TYPES = [
'posts', 'comments', 'users', 'roles', 'auth', 'settings', 'configmaps',
'plugins', 'themes', 'attachments', 'menus', 'categories', 'tags',
]
const loading = ref(false)
const error = ref('')
const logs = ref<AuditLog[]>([])
const total = ref(0)
const page = ref(1)
const size = ref(20)
// 筛选条件
const filterUsername = ref('')
const filterResourceType = ref('')
const filterMethod = ref('')
const filterResult = ref('')
const filterKeyword = ref('')
const filterStartTime = ref('')
const filterEndTime = ref('')
const selectedLog = ref<AuditLog | null>(null)
const detailVisible = ref(false)
const hasActiveFilter = computed(
() =>
filterUsername.value ||
filterResourceType.value ||
filterMethod.value ||
filterResult.value ||
filterKeyword.value ||
filterStartTime.value ||
filterEndTime.value,
)
function buildQuery(): string {
const params = new URLSearchParams()
params.set('page', String(page.value))
params.set('size', String(size.value))
params.set('sort', 'metadata.creationTimestamp,desc')
if (filterUsername.value.trim()) {
params.append('fieldSelector', `spec.username=${filterUsername.value.trim()}`)
}
if (filterResourceType.value) {
params.append('fieldSelector', `spec.resourceType=${filterResourceType.value}`)
}
if (filterMethod.value) {
params.append('fieldSelector', `spec.method=${filterMethod.value}`)
}
if (filterResult.value) {
params.set('result', filterResult.value)
}
if (filterKeyword.value.trim()) {
params.set('keyword', filterKeyword.value.trim())
}
const start = localDateTimeToInstant(filterStartTime.value)
const end = localDateTimeToInstant(filterEndTime.value)
if (start) {
params.set('startTime', start)
}
if (end) {
params.set('endTime', end)
}
return params.toString()
}
async function fetchLogs() {
loading.value = true
error.value = ''
try {
const response = await fetch(`${QUERY_ENDPOINT}?${buildQuery()}`)
if (!response.ok) {
throw new Error(`查询失败(HTTP ${response.status})`)
}
const result = (await response.json()) as ListResult<AuditLog>
logs.value = result.items ?? []
total.value = result.total ?? 0
} catch (e) {
error.value = e instanceof Error ? e.message : String(e)
logs.value = []
total.value = 0
} finally {
loading.value = false
}
}
function resetFilter() {
filterUsername.value = ''
filterResourceType.value = ''
filterMethod.value = ''
filterResult.value = ''
filterKeyword.value = ''
filterStartTime.value = ''
filterEndTime.value = ''
}
watch([filterUsername, filterResourceType, filterMethod, filterResult], () => {
page.value = 1
fetchLogs()
})
function applyFilters() {
page.value = 1
fetchLogs()
}
watch([page, size], () => fetchLogs())
function openDetail(log: AuditLog) {
selectedLog.value = log
detailVisible.value = true
}
onMounted(fetchLogs)
</script>
<template>
<div class="audit-page">
<VPageHeader title="操作审计">
<template #icon>
<span class="audit-logo">监</span>
</template>
<template #actions>
<VSpace>
<VButton :loading="loading" type="default" @click="fetchLogs">
<template #icon>
<IconRefreshLine class="h-full w-full" />
</template>
刷新
</VButton>
</VSpace>
</template>
</VPageHeader>
<div class="audit-body">
<!-- 筛选栏(只读查询,无任何修改/删除入口) -->
<VCard :body-class="['audit-filter']">
<div class="filter-grid">
<label class="filter-item">
<span>操作者</span>
<input
v-model="filterUsername"
type="text"
placeholder="用户名,精确匹配"
/>
</label>
<label class="filter-item">
<span>资源类型</span>
<select v-model="filterResourceType">
<option value="">全部</option>
<option v-for="t in RESOURCE_TYPES" :key="t" :value="t">{{ t }}</option>
</select>
</label>
<label class="filter-item">
<span>动作</span>
<select v-model="filterMethod">
<option value="">全部</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="PATCH">PATCH</option>
</select>
</label>
<label class="filter-item">
<span>结果</span>
<select v-model="filterResult">
<option value="">全部</option>
<option value="success">成功</option>
<option value="failure">失败</option>
</select>
</label>
<label class="filter-item">
<span>关键字</span>
<input
v-model="filterKeyword"
type="text"
placeholder="资源名称 / 路径模糊匹配"
@keyup.enter="applyFilters"
/>
</label>
<label class="filter-item">
<span>开始时间</span>
<input v-model="filterStartTime" type="datetime-local" @change="applyFilters" />
</label>
<label class="filter-item">
<span>结束时间</span>
<input v-model="filterEndTime" type="datetime-local" @change="applyFilters" />
</label>
<div class="filter-actions">
<VButton size="sm" @click="applyFilters">查询</VButton>
<VButton size="sm" :disabled="!hasActiveFilter" @click="resetFilter">重置</VButton>
</div>
</div>
</VCard>
<VAlert v-if="error" class="audit-error" type="error" :closable="true" :title="error" />
<VCard :body-class="['!p-0']">
<VLoading v-if="loading && !logs.length" />
<template v-else>
<VEmpty
v-if="!logs.length"
title="暂无审计记录"
:message="hasActiveFilter ? '没有匹配当前筛选条件的记录' : '插件启用后,后台写操作与登录事件会自动记录在这里'"
>
<template #actions>
<VButton @click="hasActiveFilter ? resetFilter() : fetchLogs()">
{{ hasActiveFilter ? '清除筛选' : '刷新' }}
</VButton>
</template>
</VEmpty>
<template v-else>
<VEntity
v-for="log in logs"
:key="log.metadata.name"
class="audit-row"
@click="openDetail(log)"
>
<template #start>
<VEntityField :title="displayUsername(log.spec.username)">
<template #description>
<span class="row-sub">{{ formatTime(log.metadata.creationTimestamp) }}</span>
</template>
</VEntityField>
<VEntityField :title="log.spec.method">
<template #extra>
<span class="method-badge" :class="methodBadgeClass(log.spec.method)">
{{ log.spec.method }}
</span>
</template>
</VEntityField>
<VEntityField>
<template #title>
<span class="resource-text">
{{ log.spec.resourceType }}
<template v-if="log.spec.resourceName">/ {{ log.spec.resourceName }}</template>
</span>
</template>
<template #description>
<span class="row-sub">{{ log.spec.path }}</span>
</template>
</VEntityField>
</template>
<template #end>
<VEntityField>
<template #extra>
<span
class="status-badge"
:class="isSuccessful(log.spec.statusCode) ? 'status-ok' : 'status-fail'"
>
{{ log.spec.statusCode }}
</span>
</template>
</VEntityField>
<VEntityField :title="log.spec.remoteIp" />
</template>
</VEntity>
</template>
</template>
</VCard>
<div v-if="total > 0" class="audit-pagination">
<VPagination
v-model:page="page"
v-model:size="size"
:total="total"
:page-label="'页码'"
:size-label="'每页条数'"
:total-label="`共 ${total} 条`"
:size-options="[10, 20, 50]"
/>
</div>
</div>
<AuditLogDetail v-model:visible="detailVisible" :log="selectedLog" />
</div>
</template>
<style scoped>
.audit-page {
--audit-green: #4ccba0;
--audit-dark: #0e1731;
--audit-red: #d71d1d;
}
.audit-body {
padding: 1rem 1.25rem 2rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
.audit-logo {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 0.375rem;
background: var(--audit-dark);
color: #fff;
font-size: 0.8rem;
}
.audit-filter {
padding: 0.75rem 1rem;
}
.filter-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0.75rem 1rem;
align-items: end;
}
.filter-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.75rem;
color: #666;
}
.filter-item input,
.filter-item select {
height: 2rem;
padding: 0 0.5rem;
border: 1px solid #ddd;
border-radius: 0.375rem;
font-size: 0.8125rem;
background: #fff;
min-width: 0;
}
.filter-item input:focus,
.filter-item select:focus {
outline: none;
border-color: var(--audit-green);
}
.filter-actions {
display: flex;
gap: 0.5rem;
}
.audit-error {
--tw-ring-color: transparent;
}
.audit-row {
cursor: pointer;
}
.row-sub {
font-size: 0.75rem;
color: #999;
max-width: 22rem;
display: inline-block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.resource-text {
font-size: 0.8125rem;
}
.method-badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.25rem;
font-size: 0.6875rem;
font-weight: 600;
font-family: ui-monospace, monospace;
color: #fff;
background: #6b7280;
}
.method-post { background: #1e7ee0; }
.method-put { background: #d97706; }
.method-delete { background: var(--audit-red); }
.method-patch { background: #7c3aed; }
.status-badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.25rem;
font-size: 0.6875rem;
font-weight: 600;
font-family: ui-monospace, monospace;
}
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.status-fail { color: var(--audit-red); background: rgba(215, 29, 29, 0.12); }
.audit-pagination {
display: flex;
justify-content: center;
padding-bottom: 1rem;
}
</style>