feat(roles): role management pages (super-admin)
- /roles — role table with create dialog and a permission-matrix sheet: collapsible per-module sections (selected/total counts, role's own modules start expanded) and a key/description filter that force- expands matches; super-admin role is read-only - /admin-users — user search (Enter to run) with role assignment dialog; editing your own roles is blocked Both nav items gate on auth:role:* keys, which only super-admin holds. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { PERM, requirePermission } from '@/auth/permissions'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import { toast } from 'sonner'
|
||||
import type { RoleUser } from '@/api/types'
|
||||
import { fetchRoles, searchRoleUsers, syncUserRoles } from '@/api/modules/roles'
|
||||
import { useAuthStore } from '@/auth/store'
|
||||
import { handleApiError } from '@/lib/errors'
|
||||
import { DataTable } from '@/components/data-table/data-table'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
|
||||
export const Route = createFileRoute('/_authed/admin-users')({
|
||||
beforeLoad: () => requirePermission(PERM.ROLE_ASSIGN),
|
||||
component: AdminUsersPage,
|
||||
})
|
||||
|
||||
function AdminUsersPage() {
|
||||
const myUid = useAuthStore((s) => s.user?.uid)
|
||||
// search applies on Enter to avoid a request per keystroke
|
||||
const [queryInput, setQueryInput] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [editing, setEditing] = useState<RoleUser | null>(null)
|
||||
|
||||
const results = useQuery({
|
||||
queryKey: ['role-users', query],
|
||||
queryFn: () => searchRoleUsers(query),
|
||||
enabled: query.length > 0,
|
||||
})
|
||||
|
||||
const columns: ColumnDef<RoleUser>[] = [
|
||||
{
|
||||
header: '用户',
|
||||
cell: ({ row }) => (
|
||||
<div>
|
||||
<div className="font-medium">{row.original.display_name ?? row.original.username ?? '—'}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{row.original.email}
|
||||
<code className="ml-2 font-mono">{row.original.uid}</code>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '角色',
|
||||
cell: ({ row }) =>
|
||||
row.original.roles.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{row.original.roles.map((role) => (
|
||||
<Badge key={role} variant="secondary">
|
||||
{role}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '操作',
|
||||
cell: ({ row }) =>
|
||||
row.original.uid === myUid ? (
|
||||
<span className="text-xs text-muted-foreground">不能修改自己</span>
|
||||
) : (
|
||||
<Button size="sm" variant="outline" onClick={() => setEditing(row.original)}>
|
||||
分配角色
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title="用户角色"
|
||||
description="搜索用户并分配角色(不能修改自己的角色)"
|
||||
actions={
|
||||
<Input
|
||||
value={queryInput}
|
||||
onChange={(e) => setQueryInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') setQuery(queryInput.trim())
|
||||
}}
|
||||
placeholder="邮箱 / 用户名 / UID,回车搜索"
|
||||
className="h-8 w-64"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={results.data?.data ?? []}
|
||||
loading={query.length > 0 && results.isPending}
|
||||
emptyText={query ? '没有匹配的用户' : '输入关键字并回车搜索'}
|
||||
/>
|
||||
<AssignRolesDialog
|
||||
user={editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => void results.refetch()}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AssignRolesDialog({
|
||||
user,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
user: RoleUser | null
|
||||
onClose: () => void
|
||||
onSaved: () => void
|
||||
}) {
|
||||
const roles = useQuery({ queryKey: ['roles'], queryFn: fetchRoles, enabled: user !== null })
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setSelected(new Set(user?.roles ?? []))
|
||||
}, [user])
|
||||
|
||||
const toggle = (name: string, checked: boolean) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (checked) next.add(name)
|
||||
else next.delete(name)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (!user) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await syncUserRoles(user.uid, [...selected])
|
||||
toast.success(`已更新 ${user.display_name ?? user.email} 的角色`)
|
||||
onSaved()
|
||||
onClose()
|
||||
} catch (error) {
|
||||
handleApiError(error)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={user !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>分配角色:{user?.display_name ?? user?.email}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-2">
|
||||
{(roles.data?.data ?? []).map((role) => (
|
||||
<label key={role.name} className="flex items-center gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={selected.has(role.name)}
|
||||
onCheckedChange={(checked) => toggle(role.name, checked === true)}
|
||||
/>
|
||||
<span className="font-medium">{role.name}</span>
|
||||
{role.builtin && <Badge variant="secondary">内建</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">
|
||||
{role.name === 'super-admin' ? '全部权限' : `${role.permissions.length} 项权限`}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={save} disabled={busy}>
|
||||
{busy ? '保存中…' : '保存'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { PERM, requirePermission } from '@/auth/permissions'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import { ChevronRight, Plus } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { AdminRole } from '@/api/types'
|
||||
import {
|
||||
createRole,
|
||||
deleteRole,
|
||||
fetchPermissionCatalog,
|
||||
fetchRoles,
|
||||
syncRolePermissions,
|
||||
} from '@/api/modules/roles'
|
||||
import { useCan } from '@/auth/store'
|
||||
import { handleApiError } from '@/lib/errors'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { DataTable } from '@/components/data-table/data-table'
|
||||
import { PageHeader } from '@/components/page-header'
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
|
||||
export const Route = createFileRoute('/_authed/roles')({
|
||||
beforeLoad: () => requirePermission(PERM.ROLE_READ),
|
||||
component: RolesPage,
|
||||
})
|
||||
|
||||
function RolesPage() {
|
||||
const canCreate = useCan(PERM.ROLE_CREATE)
|
||||
const canUpdate = useCan(PERM.ROLE_UPDATE)
|
||||
const canDelete = useCan(PERM.ROLE_DELETE)
|
||||
|
||||
const roles = useQuery({ queryKey: ['roles'], queryFn: fetchRoles })
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<AdminRole | null>(null)
|
||||
|
||||
const refetch = () => void roles.refetch()
|
||||
|
||||
const remove = async (role: AdminRole) => {
|
||||
try {
|
||||
await deleteRole(role.name)
|
||||
toast.success(`已删除角色 ${role.name}`)
|
||||
refetch()
|
||||
} catch (error) {
|
||||
handleApiError(error)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnDef<AdminRole>[] = [
|
||||
{
|
||||
header: '角色',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
{row.original.builtin && <Badge variant="secondary">内建</Badge>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '权限数',
|
||||
cell: ({ row }) =>
|
||||
row.original.name === 'super-admin' ? '全部' : row.original.permissions.length,
|
||||
},
|
||||
{
|
||||
header: '用户数',
|
||||
cell: ({ row }) => row.original.users_count,
|
||||
},
|
||||
{
|
||||
header: '操作',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{canUpdate && row.original.name !== 'super-admin' && (
|
||||
<Button size="sm" variant="outline" onClick={() => setEditing(row.original)}>
|
||||
编辑权限
|
||||
</Button>
|
||||
)}
|
||||
{canDelete && !row.original.builtin && row.original.users_count === 0 && (
|
||||
<ConfirmDialog
|
||||
trigger={
|
||||
<Button size="sm" variant="ghost">
|
||||
删除
|
||||
</Button>
|
||||
}
|
||||
title={`删除角色 ${row.original.name}?`}
|
||||
confirmLabel="删除"
|
||||
destructive
|
||||
onConfirm={() => remove(row.original)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title="角色管理"
|
||||
description="角色与权限矩阵;super-admin 角色不可修改"
|
||||
actions={
|
||||
canCreate && (
|
||||
<Button onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
新建角色
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={roles.data?.data ?? []}
|
||||
loading={roles.isPending}
|
||||
emptyText="暂无角色"
|
||||
/>
|
||||
<CreateRoleDialog open={createOpen} onOpenChange={setCreateOpen} onCreated={refetch} />
|
||||
<PermissionMatrixSheet role={editing} onClose={() => setEditing(null)} onSaved={refetch} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CreateRoleDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onCreated: () => void
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const submit = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await createRole(name.trim())
|
||||
toast.success(`已创建角色 ${name.trim()}`)
|
||||
setName('')
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (error) {
|
||||
handleApiError(error)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建角色</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="role-name">角色名(小写字母、数字、连字符)</Label>
|
||||
<Input
|
||||
id="role-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="如 reviewer"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={submit} disabled={busy || !/^[a-z0-9-]+$/.test(name.trim())}>
|
||||
{busy ? '创建中…' : '创建'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function PermissionMatrixSheet({
|
||||
role,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
role: AdminRole | null
|
||||
onClose: () => void
|
||||
onSaved: () => void
|
||||
}) {
|
||||
const catalog = useQuery({
|
||||
queryKey: ['permission-catalog'],
|
||||
queryFn: fetchPermissionCatalog,
|
||||
enabled: role !== null,
|
||||
})
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [openModules, setOpenModules] = useState<Set<string>>(new Set())
|
||||
const [filter, setFilter] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const modules = useMemo(() => Object.values(catalog.data?.data ?? {}), [catalog.data])
|
||||
|
||||
useEffect(() => {
|
||||
const permissions = role?.permissions ?? []
|
||||
setSelected(new Set(permissions))
|
||||
setFilter('')
|
||||
// start with the modules the role already touches expanded
|
||||
setOpenModules(
|
||||
new Set(
|
||||
modules
|
||||
.filter((mod) =>
|
||||
Object.values(mod.groups).some((perms) =>
|
||||
Object.keys(perms).some((key) => permissions.includes(key)),
|
||||
),
|
||||
)
|
||||
.map((mod) => mod.module),
|
||||
),
|
||||
)
|
||||
}, [role, modules])
|
||||
|
||||
// filter matches key or description, case-insensitive; while filtering,
|
||||
// non-matching entries are dropped and every remaining module is expanded
|
||||
const visibleModules = useMemo(() => {
|
||||
const q = filter.trim().toLowerCase()
|
||||
if (!q) return modules
|
||||
return modules
|
||||
.map((mod) => {
|
||||
const groups: Record<string, Record<string, string>> = {}
|
||||
for (const [group, perms] of Object.entries(mod.groups)) {
|
||||
const matched = Object.entries(perms).filter(
|
||||
([key, description]) =>
|
||||
key.toLowerCase().includes(q) || description.toLowerCase().includes(q),
|
||||
)
|
||||
if (matched.length > 0) groups[group] = Object.fromEntries(matched)
|
||||
}
|
||||
return { ...mod, groups }
|
||||
})
|
||||
.filter((mod) => Object.keys(mod.groups).length > 0)
|
||||
}, [modules, filter])
|
||||
|
||||
const filtering = filter.trim().length > 0
|
||||
|
||||
const toggle = (key: string, checked: boolean) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (checked) next.add(key)
|
||||
else next.delete(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const toggleModule = (module: string) => {
|
||||
setOpenModules((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(module)) next.delete(module)
|
||||
else next.add(module)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const selectedInModule = (mod: (typeof modules)[number]) =>
|
||||
Object.values(mod.groups).reduce(
|
||||
(count, perms) => count + Object.keys(perms).filter((key) => selected.has(key)).length,
|
||||
0,
|
||||
)
|
||||
|
||||
const totalInModule = (mod: (typeof modules)[number]) =>
|
||||
Object.values(mod.groups).reduce((count, perms) => count + Object.keys(perms).length, 0)
|
||||
|
||||
const save = async () => {
|
||||
if (!role) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await syncRolePermissions(role.name, [...selected])
|
||||
toast.success(`已更新 ${role.name} 的权限(${selected.size} 项)`)
|
||||
onSaved()
|
||||
onClose()
|
||||
} catch (error) {
|
||||
handleApiError(error)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet open={role !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<SheetContent className="flex w-full flex-col sm:max-w-xl">
|
||||
<SheetHeader>
|
||||
<SheetTitle>编辑权限:{role?.name}</SheetTitle>
|
||||
<SheetDescription>已选 {selected.size} 项</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="px-4 pb-2">
|
||||
<Input
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
placeholder="筛选权限键或描述…"
|
||||
className="h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-4">
|
||||
{visibleModules.length === 0 && (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">没有匹配的权限</p>
|
||||
)}
|
||||
{visibleModules.map((mod) => {
|
||||
const open = filtering || openModules.has(mod.module)
|
||||
return (
|
||||
<div key={mod.module} className="mb-2 rounded-md border">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleModule(mod.module)}
|
||||
className="flex w-full items-center gap-2 px-3 py-2 text-sm font-semibold hover:bg-muted/40"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn('size-4 shrink-0 transition-transform', open && 'rotate-90')}
|
||||
/>
|
||||
<span className="capitalize">{mod.module}</span>
|
||||
<span className="ml-auto text-xs font-normal text-muted-foreground">
|
||||
{selectedInModule(mod)} / {totalInModule(mod)}
|
||||
</span>
|
||||
</button>
|
||||
{open && (
|
||||
<div className="border-t px-3 py-2">
|
||||
{Object.entries(mod.groups).map(([group, perms]) => (
|
||||
<div key={group} className="mb-2 last:mb-0">
|
||||
<div className="mb-1 text-xs text-muted-foreground">{group}</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{Object.entries(perms).map(([key, description]) => (
|
||||
<label key={key} className="flex items-start gap-2 text-sm">
|
||||
<Checkbox
|
||||
checked={selected.has(key)}
|
||||
onCheckedChange={(checked) => toggle(key, checked === true)}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span>
|
||||
<code className="font-mono text-xs">{key}</code>
|
||||
<span className="ml-2 text-muted-foreground">{description}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={save} disabled={busy}>
|
||||
{busy ? '保存中…' : '保存'}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user