User Role (#69)

* fix: window.DisableAnimatedMan as boolean

* chore: auto-fix linting and formatting issues

* feat: user role

* feat: use user agent_secret

* feat: hide setting when user role is not admin

* feat: new waf api

* chore: auto-fix linting and formatting issues

* fix: admin settings page

* feat: online-user setting

* fix: pagination

---------

Co-authored-by: hamster1963 <hamster1963@users.noreply.github.com>
This commit is contained in:
仓鼠
2024-12-22 23:17:20 +08:00
committed by GitHub
co-authored by hamster1963
parent 5ad915c973
commit 7fdac38291
15 changed files with 703 additions and 36 deletions
+158 -18
View File
@@ -4,6 +4,15 @@ import { ActionButtonGroup } from "@/components/action-button-group"
import { HeaderButtonGroup } from "@/components/header-button-group"
import { SettingsTab } from "@/components/settings-tab"
import { Checkbox } from "@/components/ui/checkbox"
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination"
import {
Table,
TableBody,
@@ -12,17 +21,32 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table"
import { useAuth } from "@/hooks/useAuth"
import { ip16Str } from "@/lib/utils"
import { ModelWAFApiMock, wafBlockReasons } from "@/types"
import { ModelWAF, ModelWAFApiMock, wafBlockIdentifiers, wafBlockReasons } from "@/types"
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
import { useEffect, useMemo } from "react"
import { useTranslation } from "react-i18next"
import { useSearchParams } from "react-router-dom"
import { toast } from "sonner"
import useSWR from "swr"
export default function WAFPage() {
const { t } = useTranslation()
const { data, mutate, error, isLoading } = useSWR<ModelWAFApiMock[]>("/api/v1/waf", swrFetcher)
const { profile } = useAuth()
const [searchParams, setSearchParams] = useSearchParams()
const page = Number(searchParams.get("page")) || 1
const pageSize = Number(searchParams.get("pageSize")) || 10
// 计算 offset
const offset = (page - 1) * pageSize
const { data, mutate, error, isLoading } = useSWR<ModelWAFApiMock>(
`/api/v1/waf?offset=${offset}&limit=${pageSize}`,
swrFetcher,
)
const isAdmin = profile?.role === 0
useEffect(() => {
if (error)
@@ -32,7 +56,7 @@ export default function WAFPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [error])
const columns: ColumnDef<ModelWAFApiMock>[] = [
let columns: ColumnDef<ModelWAF>[] = [
{
id: "select",
header: ({ table }) => (
@@ -68,16 +92,23 @@ export default function WAFPage() {
{
header: t("LastBlockReason"),
accessorKey: "lastBlockReason",
accessorFn: (row) => row.last_block_reason,
cell: ({ row }) => <span>{wafBlockReasons[row.original.last_block_reason] || ""}</span>,
accessorFn: (row) => row.block_reason,
cell: ({ row }) => <span>{wafBlockReasons[row.original.block_reason] || ""}</span>,
},
{
header: t("LastBlockIdentifier"),
accessorKey: "lastBlockIdentifier",
accessorFn: (row) => (
<span>{wafBlockIdentifiers[row.block_identifier] || row.block_identifier}</span>
),
},
{
header: t("LastBlockTime"),
accessorKey: "lastBlockTime",
accessorFn: (row) => row.last_block_timestamp,
accessorFn: (row) => row.block_timestamp,
cell: ({ row }) => {
const s = row.original
const date = new Date((s.last_block_timestamp || 0) * 1000)
const date = new Date((s.block_timestamp || 0) * 1000)
return <span>{date.toISOString()}</span>
},
},
@@ -102,8 +133,13 @@ export default function WAFPage() {
},
]
if (!isAdmin) {
// 非管理员隐藏操作列
columns = columns.filter((c) => c.id !== "actions")
}
const dataCache = useMemo(() => {
return data ?? []
return data?.value ?? []
}, [data])
const table = useReactTable({
@@ -114,20 +150,123 @@ export default function WAFPage() {
const selectedRows = table.getSelectedRowModel().rows
const renderPagination = () => {
if (!data?.pagination) return null
const { total } = data.pagination
const totalPages = Math.ceil(total / pageSize)
const handlePageChange = (newPage: number) => {
if (newPage < 1 || newPage > totalPages) return
setSearchParams({ page: newPage.toString(), pageSize: pageSize.toString() })
}
// 计算要显示的页码范围
const getPageNumbers = () => {
const pages: number[] = []
const maxVisiblePages = 5
if (totalPages <= maxVisiblePages) {
return Array.from({ length: totalPages }, (_, i) => i + 1)
}
// 始终显示第一页
pages.push(1)
let startPage = Math.max(2, page - 1)
let endPage = Math.min(totalPages - 1, page + 1)
if (page <= 3) {
endPage = Math.min(maxVisiblePages - 1, totalPages - 1)
} else if (page >= totalPages - 2) {
startPage = Math.max(2, totalPages - (maxVisiblePages - 2))
}
if (startPage > 2) {
pages.push(-1) // 表示省略号
}
for (let i = startPage; i <= endPage; i++) {
pages.push(i)
}
if (endPage < totalPages - 1) {
pages.push(-1) // 表示省略号
}
// 始终显示最后一页
if (totalPages > 1) {
pages.push(totalPages)
}
return pages
}
return (
<div className="flex items-center justify-between px-2 py-4">
<div className="text-sm text-muted-foreground">
{t("Total")}: {total}
</div>
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={() => handlePageChange(page - 1)}
className={
page <= 1 ? "pointer-events-none opacity-50" : "cursor-pointer"
}
/>
</PaginationItem>
{getPageNumbers().map((pageNum, idx) =>
pageNum === -1 ? (
<PaginationItem key={`ellipsis-${idx}`}>
<PaginationEllipsis />
</PaginationItem>
) : (
<PaginationItem key={pageNum}>
<PaginationLink
onClick={() => handlePageChange(pageNum)}
isActive={pageNum === page}
>
{pageNum}
</PaginationLink>
</PaginationItem>
),
)}
<PaginationItem>
<PaginationNext
onClick={() => handlePageChange(page + 1)}
className={
page >= totalPages
? "pointer-events-none opacity-50"
: "cursor-pointer"
}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
)
}
return (
<div className="px-3">
<SettingsTab className="mt-6 w-full" />
<div className="flex mt-4 mb-4">
<HeaderButtonGroup
className="flex-2 flex gap-2 ml-auto"
delete={{
fn: deleteWAF,
id: selectedRows.map((r) => ip16Str(r.original.ip ?? "")),
mutate: mutate,
}}
>
<></>
</HeaderButtonGroup>
{isAdmin && (
<HeaderButtonGroup
className="flex-2 flex gap-2 ml-auto"
delete={{
fn: deleteWAF,
id: selectedRows.map((r) => ip16Str(r.original.ip ?? "")),
mutate: mutate,
}}
>
<></>
</HeaderButtonGroup>
)}
</div>
<Table>
<TableHeader>
@@ -174,6 +313,7 @@ export default function WAFPage() {
)}
</TableBody>
</Table>
{renderPagination()}
</div>
)
}