feat: paginate admin audit logs

Show ten entries per page with localized responsive controls. Add server-side pagination for the complete audit history, retain the legacy array response, and cover page boundaries, validation and access control.
This commit is contained in:
2026-11-01 19:22:32 +08:00
parent f8cef413d6
commit cfa3799250
6 changed files with 161 additions and 5 deletions
+2
View File
@@ -38,6 +38,8 @@ Vue 3 + TypeScript + Vite,使用 vue-i18n 管理界面文案。当前首页支
`/admin` 提供登录、Markdown 公告草稿/发布、镜像展示信息与使用帮助、任务命令和日志、全局/单个镜像调度配置、站点标识/头像/首页相关链接/页脚友链/下载项、管理员和公告编辑账户,以及操作记录。同步间隔遵循 tunasync 的原生语义:从上次同步结束后开始计算,单位为分钟。任务命令只表示已提交,最终状态以 Worker 为准。
操作记录按时间倒序,每页 10 条;超过一页时显示分页控制,可查看全部历史记录。接口 `/api/v1/admin/audit?page=1` 返回当前页、总条数和总页数,未带 `page` 的旧版请求继续返回最近 200 条数组。
## 后端与部署
后端使用 Go 标准库 HTTP、SQLite 和 TOML 解析器,不依赖数据库外部服务。详细部署、权限、备份和回退操作见 [deploy/README.md](deploy/README.md)。
+89
View File
@@ -0,0 +1,89 @@
package main
import (
"encoding/json"
"fmt"
"testing"
)
func TestAuditPagination(t *testing.T) {
c := fixture(t)
c.login("admin")
type entry struct {
ID int `json:"id"`
}
type auditPage struct {
Items []entry `json:"items"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
Total int `json:"total"`
TotalPages int `json:"totalPages"`
}
readPage := func(t *testing.T, page int) auditPage {
t.Helper()
w := c.call("GET", fmt.Sprintf("/api/v1/admin/audit?page=%d", page), nil, false)
status(t, w, 200)
var result auditPage
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
for _, count := range []int{0, 10, 11, 205} {
t.Run(fmt.Sprint(count), func(t *testing.T) {
tx, err := c.app.db.Begin()
if err != nil {
t.Fatal(err)
}
defer tx.Rollback()
if _, err := tx.Exec("DELETE FROM audit"); err != nil {
t.Fatal(err)
}
for id := 1; id <= count; id++ {
if _, err := tx.Exec("INSERT INTO audit(id,username,action,target,result,created) VALUES(?,'admin','record_save','settings/site','success',?)", id, id); err != nil {
t.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
pages, seen := max(1, (count+9)/10), 0
for page := 1; page <= pages; page++ {
result := readPage(t, page)
wantRows := min(10, count-seen)
if result.Items == nil || result.Page != page || result.PageSize != 10 || result.Total != count || result.TotalPages != pages || len(result.Items) != wantRows {
t.Fatalf("incorrect pagination for page %d: %+v", page, result)
}
for _, item := range result.Items {
if item.ID != count-seen {
t.Fatalf("duplicate, skipped or unordered record: want %d, got %d", count-seen, item.ID)
}
seen++
}
}
if seen != count {
t.Fatal("older records are inaccessible")
}
last := readPage(t, 999999)
if last.Page != pages || len(last.Items) != max(0, count-(pages-1)*10) {
t.Fatalf("out-of-range page was not clamped: %+v", last)
}
w := c.call("GET", "/api/v1/admin/audit", nil, false)
status(t, w, 200)
var legacy []entry
if err := json.Unmarshal(w.Body.Bytes(), &legacy); err != nil || len(legacy) != min(200, count) {
t.Fatal("already-open older admin pages lost their array response")
}
})
}
for _, page := range []string{"", "0", "-1", "abc", "1.5", "99999999999999999999999"} {
status(t, c.call("GET", "/api/v1/admin/audit?page="+page, nil, false), 400)
}
}
func TestAuditPaginationRequiresAdmin(t *testing.T) {
c := fixture(t)
status(t, c.call("GET", "/api/v1/admin/audit?page=1", nil, false), 401)
c.login("editor")
status(t, c.call("GET", "/api/v1/admin/audit?page=1", nil, false), 403)
}
+45 -1
View File
@@ -15,6 +15,7 @@ import (
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
@@ -331,7 +332,33 @@ func (a *App) auditList(w http.ResponseWriter, r *http.Request) {
if _, ok := a.require(w, r, true); !ok {
return
}
rows, err := a.db.Query("SELECT id,username,action,target,result,created FROM audit ORDER BY id DESC LIMIT 200")
page, pageSize := 1, 10
paginated := r.URL.Query().Has("page")
if paginated {
var err error
page, err = strconv.Atoi(r.URL.Query().Get("page"))
if err != nil || page < 1 {
fail(w, 400, "INVALID_INPUT")
return
}
}
tx, err := a.db.BeginTx(r.Context(), nil)
if err != nil {
a.internal(w, err)
return
}
defer tx.Rollback()
total, totalPages, limit, offset := 0, 1, 200, 0
if paginated {
if err := tx.QueryRowContext(r.Context(), "SELECT COUNT(*) FROM audit").Scan(&total); err != nil {
a.internal(w, err)
return
}
totalPages = max(1, (total+pageSize-1)/pageSize)
page = min(page, totalPages)
limit, offset = pageSize, (page-1)*pageSize
}
rows, err := tx.QueryContext(r.Context(), "SELECT id,username,action,target,result,created FROM audit ORDER BY id DESC LIMIT ? OFFSET ?", limit, offset)
if err != nil {
a.internal(w, err)
return
@@ -347,6 +374,23 @@ func (a *App) auditList(w http.ResponseWriter, r *http.Request) {
}
out = append(out, map[string]any{"id": id, "username": username, "action": action, "target": target, "result": result, "created": created})
}
if err := rows.Err(); err != nil {
a.internal(w, err)
return
}
if err := rows.Close(); err != nil {
a.internal(w, err)
return
}
if err := tx.Commit(); err != nil {
a.internal(w, err)
return
}
if paginated {
respond(w, 200, map[string]any{"items": out, "page": page, "pageSize": pageSize, "total": total, "totalPages": totalPages})
return
}
// Keep the array response for already-open admin pages from older releases.
respond(w, 200, out)
}
func (a *App) users(w http.ResponseWriter, r *http.Request) {
+1
View File
@@ -17,6 +17,7 @@ export interface SyncConfigMirror { name: string; provider: string; upstream: st
export interface SyncConfig { worker: string; baseHash: string; global: SyncNumbers; mirrors: SyncConfigMirror[]; canAdd: boolean }
export interface ConfigVersion { id: string; files: Record<string, { before: string | null; after: string | null }> | null; baseHash: string; status: string; created: number; username: string }
export interface AuditEntry { id: number; username: string; action: string; target: string; result: string; created: number }
export interface AuditPage { items: AuditEntry[]; page: number; pageSize: number; total: number; totalPages: number }
export interface AdminUser { id: number; username: string; role: string; created: number }
let csrf = ''
+23 -4
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { api, ApiError, jsonBody, setSession, type AdminSession, type AdminUser, type AnnouncementContent, type AuditEntry, type ConfigVersion, type ContentRecord, type MirrorMetadata, type Overview, type SiteSettings, type SyncConfig, type SyncConfigMirror, type SyncJob } from '../api'
import { api, ApiError, jsonBody, setSession, type AdminSession, type AdminUser, type AnnouncementContent, type AuditPage, type ConfigVersion, type ContentRecord, type MirrorMetadata, type Overview, type SiteSettings, type SyncConfig, type SyncConfigMirror, type SyncJob } from '../api'
import { supportedLocales } from '../locales'
import MarkdownContent from './MarkdownContent.vue'
@@ -20,7 +20,7 @@ const articles = ref<ContentRecord<AnnouncementContent>[]>([])
const metadata = ref<ContentRecord<MirrorMetadata>[]>([])
const settings = ref<ContentRecord<SiteSettings> | null>(null)
const users = ref<AdminUser[]>([])
const audit = ref<AuditEntry[]>([])
const audit = ref<AuditPage>({ items: [], page: 1, pageSize: 10, total: 0, totalPages: 1 })
const search = ref('')
const jobs = computed(() => (overview.value?.jobs || []).filter(job => `${job.name} ${job.upstream}`.toLowerCase().includes(search.value.toLowerCase())).sort((a, b) => a.name.localeCompare(b.name, 'en')))
const articlesEditor = ref<ContentRecord<AnnouncementContent> | null>(null)
@@ -62,6 +62,7 @@ async function run(action: () => Promise<void>) {
} finally { busy.value = false }
}
async function loadOverview() { overview.value = await api<Overview>('/admin/overview') }
async function loadAudit(page = 1) { audit.value = await api<AuditPage>(`/admin/audit?page=${page}`) }
function moveRelatedLink(index: number, offset: number) {
const links = settings.value?.data.relatedLinks
const destination = index + offset
@@ -76,7 +77,7 @@ async function loadTab(value: string) {
if (value === 'settings') settings.value = (await api<ContentRecord<SiteSettings>[]>('/admin/records/settings'))[0] || null
if (value === 'config') { config.value = await api('/admin/config'); versions.value = await api('/admin/config/versions'); draft.value = null; selectedConfig.value = ''; mirrorConfig.value = null }
if (value === 'users' && session.value?.role === 'admin') users.value = await api('/admin/users')
if (value === 'audit') audit.value = await api('/admin/audit')
if (value === 'audit') await loadAudit()
}
function changeTab(value: string) { void run(async () => { tab.value = value; await loadTab(value) }) }
async function login() {
@@ -211,7 +212,17 @@ onBeforeUnmount(() => clearInterval(poll))
<h3>{{ t('admin.changePassword') }}</h3><p>{{ t('admin.passwordHint') }}</p><form class="admin-form admin-login" @submit.prevent="run(changePassword)"><label>{{ t('admin.currentPassword') }}<input v-model="passwords.currentPassword" type="password" autocomplete="current-password" required /></label><label>{{ t('admin.newPassword') }}<input v-model="passwords.newPassword" type="password" autocomplete="new-password" minlength="12" maxlength="256" required /></label><label>{{ t('admin.confirmPassword') }}<input v-model="passwords.confirm" type="password" autocomplete="new-password" minlength="12" maxlength="256" required /></label><button class="primary" :disabled="busy">{{ t('admin.changePassword') }}</button></form>
<template v-if="session.role === 'admin'"><h3>{{ t('admin.users') }}</h3><div class="admin-table-wrap"><table><thead><tr><th>{{ t('admin.username') }}</th><th>{{ t('admin.role') }}</th></tr></thead><tbody><tr v-for="user in users" :key="user.id"><td>{{ user.username }}</td><td>{{ t(`admin.${user.role}`) }}</td></tr></tbody></table></div><h3>{{ t('admin.newUser') }}</h3><form class="admin-form admin-login" @submit.prevent="run(createUser)"><label>{{ t('admin.username') }}<input v-model="newUser.username" autocomplete="off" pattern="[a-zA-Z0-9][a-zA-Z0-9_.+\-]*" required /></label><label>{{ t('admin.password') }}<input v-model="newUser.password" type="password" autocomplete="new-password" minlength="12" maxlength="256" required /></label><label>{{ t('admin.role') }}<select v-model="newUser.role"><option value="admin">{{ t('admin.admin') }}</option><option value="editor">{{ t('admin.editor') }}</option></select></label><button class="primary" :disabled="busy">{{ t('admin.newUser') }}</button></form></template>
</template>
<div v-if="tab === 'audit'" class="admin-table-wrap"><table><thead><tr><th>{{ t('admin.time') }}</th><th>{{ t('admin.actor') }}</th><th>{{ t('admin.action') }}</th><th>{{ t('admin.target') }}</th><th>{{ t('admin.result') }}</th></tr></thead><tbody><tr v-for="entry in audit" :key="entry.id"><td>{{ date(entry.created) }}</td><td>{{ entry.username }}</td><td>{{ eventLabel(entry.action) }}</td><td class="file-name">{{ entry.target }}</td><td>{{ eventLabel(entry.result) }}</td></tr></tbody></table></div>
<template v-if="tab === 'audit'">
<div class="admin-table-wrap"><table id="admin-audit-table"><thead><tr><th>{{ t('admin.time') }}</th><th>{{ t('admin.actor') }}</th><th>{{ t('admin.action') }}</th><th>{{ t('admin.target') }}</th><th>{{ t('admin.result') }}</th></tr></thead><tbody><tr v-for="entry in audit.items" :key="entry.id"><td>{{ date(entry.created) }}</td><td>{{ entry.username }}</td><td>{{ eventLabel(entry.action) }}</td><td class="file-name">{{ entry.target }}</td><td>{{ eventLabel(entry.result) }}</td></tr></tbody></table><p v-if="!audit.items.length">{{ t('admin.empty') }}</p></div>
<nav v-if="audit.totalPages > 1" class="admin-pagination" :aria-label="t('admin.auditPagination')">
<span>{{ t('admin.auditTotal', { total: n(audit.total) }) }}</span>
<div class="admin-page-controls">
<button :disabled="busy || audit.page <= 1" aria-controls="admin-audit-table" @click="run(() => loadAudit(audit.page - 1))">{{ t('admin.previousPage') }}</button>
<span role="status" aria-live="polite">{{ t('admin.pagePosition', { page: n(audit.page), pages: n(audit.totalPages) }) }}</span>
<button :disabled="busy || audit.page >= audit.totalPages" aria-controls="admin-audit-table" @click="run(() => loadAudit(audit.page + 1))">{{ t('admin.nextPage') }}</button>
</div>
</nav>
</template>
</template>
<dialog ref="confirmDialog" class="admin-confirm" :aria-label="t('admin.confirm')" @close="confirmation = null"><p>{{ confirmation?.message }}</p><div class="admin-actions"><button @click="confirmDialog?.close()">{{ t('admin.cancel') }}</button><button class="primary" @click="confirmed">{{ t('admin.confirm') }}</button></div></dialog>
</section>
@@ -234,6 +245,11 @@ textarea { resize: vertical; line-height: 1.7; } .check { flex-direction: row; a
.admin-form > button { justify-self: start; } .admin-columns { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 18px; } .admin-array { display: flex; flex-wrap: wrap; gap: 12px; align-items: end; padding: 14px 0; border-bottom: 1px solid var(--line); } .admin-array label { flex: 1; min-width: 160px; }
.admin-related-links > button { margin-top: 16px; } .admin-related-links .admin-actions { gap: 6px; }
.admin-table-wrap { max-width: 100%; overflow: auto; margin: 20px 0; } table { width: 100%; border-collapse: collapse; font-size: 14px; } th, td { padding: 12px 10px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: middle; } thead th { font-weight: 700; white-space: nowrap; } tbody th { font-weight: 500; }
.admin-pagination, .admin-page-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
.admin-pagination { justify-content: space-between; font-size: 14px; }
.admin-page-controls { gap: 10px; font-variant-numeric: tabular-nums; }
.admin-page-controls > span { text-align: center; }
.admin-page-controls button:disabled { cursor: default; }
tr[data-status='syncing'] { background: color-mix(in srgb, var(--blue) 16%,transparent); } tr[data-status='failed'] { background: #df4d4d1c; } .row-actions { gap: 6px; min-width: 260px; } .row-actions button { font-size: 12px; padding: 4px 8px; min-height: 32px; }
.admin-summary { display: flex; flex-wrap: wrap; gap: 28px 50px; } dt { color: var(--muted); font-size: 14px; } dd { margin: 10px 0 0; font-size: 24px; overflow-wrap: anywhere; }
.admin-editor { margin: 30px 0; padding: 24px; border: 1px solid var(--line); border-radius: 5px; } .admin-editor h3 { margin-top: 0; } .admin-search { max-width: 360px; }
@@ -241,6 +257,9 @@ tr[data-status='syncing'] { background: color-mix(in srgb, var(--blue) 16%,trans
.image-field { display: grid; gap: 10px; align-content: start; } .image-field img { max-width: 230px; height: 65px; object-fit: contain; object-position: left; } .upload-label { font-size: 12px; } .upload-label input { font-size: 12px; }
.admin-confirm { width: min(480px,calc(100% - 32px)); padding: 26px; border: 1px solid var(--line); border-radius: 6px; color: var(--ink); background: var(--panel); } .admin-confirm::backdrop { background: #0008; } .admin-confirm p { margin: 0 0 24px; line-height: 1.8; }
@media(max-width:700px) {
.admin-pagination { align-items: start; gap: 12px; }
.admin-page-controls { width: 100%; justify-content: space-between; gap: 6px; }
.admin-page-controls button { min-height: 42px; padding: 7px 10px; }
.jobs-table table, .jobs-table tbody { display: block; }
.jobs-table thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0,0,0,0); }
.jobs-table tr { display: grid; grid-template-columns: minmax(0,1fr) auto auto; gap: 12px; padding: 16px 10px; border-bottom: 1px solid var(--line); }
+1
View File
@@ -1,4 +1,5 @@
const pairs = {
auditPagination: ['操作记录分页', 'Audit log pagination'], auditTotal: ['共 {total} 条记录', '{total} entries'], previousPage: ['上一页', 'Previous'], nextPage: ['下一页', 'Next'], pagePosition: ['第 {page} / {pages} 页', 'Page {page} of {pages}'],
relatedLinks: ['首页相关链接', 'Home page related links'], linkType: ['链接类型', 'Link type'], urlLink: ['网址', 'URL'], helpLink: ['软件源使用帮助', 'Mirror usage guides'], linkEntry: ['相关链接 {index}', 'Related link {index}'], moveUp: ['上移', 'Move up'], moveDown: ['下移', 'Move down'],
helpChinese: ['使用说明(中文,Markdown)', 'Usage guide (Chinese, Markdown)'], descriptionLanguage: ['介绍语言', 'Description language'],
contentLanguage: ['内容语言', 'Content language'],