feat(users): add user admin section and delegate login authorization to API
This commit is contained in:
@@ -0,0 +1,475 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { PERM, requirePermission } from '@/auth/permissions'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { Eye, Search, Shield } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import type { PlatformUser } from '@/api/types'
|
||||
import { fetchUsers, updateUserStatus } from '@/api/modules/users'
|
||||
import { fetchRoles, 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 { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-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 {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { UserDetailSheet } from '@/features/users/user-detail-sheet'
|
||||
|
||||
export const Route = createFileRoute('/_authed/users/')({
|
||||
beforeLoad: () => requirePermission(PERM.ROLE_ASSIGN),
|
||||
component: UsersPage,
|
||||
})
|
||||
|
||||
function UsersPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const myUid = useAuthStore((s) => s.user?.uid)
|
||||
|
||||
// Filter state
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [q, setQ] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'true' | 'false'>('all')
|
||||
const [isRobotFilter, setIsRobotFilter] = useState<'all' | 'true' | 'false'>('all')
|
||||
const [roleFilter, setRoleFilter] = useState<string>('all')
|
||||
const [page, setPage] = useState(1)
|
||||
const pageSize = 20
|
||||
|
||||
// Selected user state for modals
|
||||
const [detailUid, setDetailUid] = useState<string | null>(null)
|
||||
const [assigningUser, setAssigningUser] = useState<PlatformUser | null>(null)
|
||||
const [togglingUser, setTogglingUser] = useState<{ user: PlatformUser; targetStatus: boolean } | null>(null)
|
||||
|
||||
// Available roles query for filter dropdown
|
||||
const rolesQuery = useQuery({ queryKey: ['roles'], queryFn: fetchRoles })
|
||||
|
||||
// Users listing query
|
||||
const usersQuery = useQuery({
|
||||
queryKey: ['users-list', { q, statusFilter, isRobotFilter, roleFilter, page }],
|
||||
queryFn: () =>
|
||||
fetchUsers({
|
||||
q: q || undefined,
|
||||
status: statusFilter === 'all' ? undefined : statusFilter === 'true',
|
||||
is_robot: isRobotFilter === 'all' ? undefined : isRobotFilter === 'true',
|
||||
role: roleFilter === 'all' ? undefined : roleFilter,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}),
|
||||
})
|
||||
|
||||
const refresh = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['users-list'] })
|
||||
if (detailUid) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['users', detailUid] })
|
||||
}
|
||||
}
|
||||
|
||||
const handleStatusToggle = async (user: PlatformUser, newStatus: boolean) => {
|
||||
try {
|
||||
await updateUserStatus(user.uid, newStatus)
|
||||
toast.success(`已${newStatus ? '启用' : '禁用'}用户 ${user.display_name ?? user.username ?? user.uid}`)
|
||||
refresh()
|
||||
} catch (error) {
|
||||
handleApiError(error)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnDef<PlatformUser>[] = [
|
||||
{
|
||||
header: '用户',
|
||||
cell: ({ row }) => {
|
||||
const u = row.original
|
||||
return (
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="size-9">
|
||||
<AvatarImage src={u.avatar ?? undefined} alt="" />
|
||||
<AvatarFallback className="text-xs font-semibold">
|
||||
{(u.display_name ?? u.username ?? 'U').slice(0, 1).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 font-medium">
|
||||
<span>{u.display_name ?? u.username ?? '—'}</span>
|
||||
{u.sid_display && (
|
||||
<Badge variant="outline" className="font-mono text-[10px] px-1 py-0 h-4">
|
||||
{u.sid_display}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<code className="font-mono">{u.uid}</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
header: '联系方式',
|
||||
cell: ({ row }) => {
|
||||
const u = row.original
|
||||
return (
|
||||
<div className="text-xs space-y-0.5">
|
||||
<div>{u.email ?? '—'}</div>
|
||||
{u.phone && <div className="text-muted-foreground">{u.phone}</div>}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
header: '类型',
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.is_robot ? 'secondary' : 'outline'}>
|
||||
{row.original.is_robot ? '机器人' : '真人'}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '角色',
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-wrap gap-1 max-w-[200px]">
|
||||
{row.original.roles && row.original.roles.length > 0 ? (
|
||||
row.original.roles.map((role) => (
|
||||
<Badge key={role} variant="secondary" className="text-[11px]">
|
||||
{role}
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">—</span>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '账号状态',
|
||||
cell: ({ row }) => {
|
||||
const u = row.original
|
||||
const isSelf = u.uid === myUid
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={u.status}
|
||||
disabled={isSelf}
|
||||
onCheckedChange={(checked) => {
|
||||
if (!checked) {
|
||||
setTogglingUser({ user: u, targetStatus: false })
|
||||
} else {
|
||||
void handleStatusToggle(u, true)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{u.status ? '已启用' : '已禁用'}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
header: '注册时间',
|
||||
cell: ({ row }) => (
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{new Date(row.original.created_at).toLocaleDateString('zh-CN')}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: '操作',
|
||||
cell: ({ row }) => {
|
||||
const u = row.original
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => setDetailUid(u.uid)}
|
||||
title="查看详情"
|
||||
>
|
||||
<Eye className="size-3.5 mr-1" />
|
||||
详情
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setAssigningUser(u)}
|
||||
title="分配角色"
|
||||
>
|
||||
<Shield className="size-3.5 mr-1" />
|
||||
角色
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const pagination = usersQuery.data?.pagination
|
||||
const totalPages = pagination?.total_pages ?? 1
|
||||
const totalCount = pagination?.total_count ?? 0
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title="用户列表"
|
||||
description="查看与管理平台注册用户账号、启用/禁用状态及角色分配"
|
||||
/>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="mb-4 flex flex-wrap items-center gap-3 rounded-lg border bg-card p-3 shadow-xs">
|
||||
<div className="relative flex-1 min-w-[220px]">
|
||||
<Search className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
setQ(searchInput.trim())
|
||||
setPage(1)
|
||||
}
|
||||
}}
|
||||
placeholder="搜索邮箱 / 用户名 / 昵称 / 手机号 / UID / SID (回车搜索)"
|
||||
className="pl-8 h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Filter */}
|
||||
<Select
|
||||
value={statusFilter}
|
||||
onValueChange={(val) => {
|
||||
setStatusFilter(val as 'all' | 'true' | 'false')
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-[120px]">
|
||||
<SelectValue placeholder="账号状态" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">全部状态</SelectItem>
|
||||
<SelectItem value="true">正常启用</SelectItem>
|
||||
<SelectItem value="false">已禁用</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* Robot Filter */}
|
||||
<Select
|
||||
value={isRobotFilter}
|
||||
onValueChange={(val) => {
|
||||
setIsRobotFilter(val as 'all' | 'true' | 'false')
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-[120px]">
|
||||
<SelectValue placeholder="账号类型" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">全部类型</SelectItem>
|
||||
<SelectItem value="false">真人账号</SelectItem>
|
||||
<SelectItem value="true">机器人账号</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* Role Filter */}
|
||||
<Select
|
||||
value={roleFilter}
|
||||
onValueChange={(val) => {
|
||||
setRoleFilter(val)
|
||||
setPage(1)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-[130px]">
|
||||
<SelectValue placeholder="筛选角色" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">全部角色</SelectItem>
|
||||
{(rolesQuery.data?.data ?? []).map((r) => (
|
||||
<SelectItem key={r.name} value={r.name}>
|
||||
{r.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={usersQuery.data?.data ?? []}
|
||||
loading={usersQuery.isPending}
|
||||
emptyText="暂无符合条件的用户"
|
||||
/>
|
||||
|
||||
{/* Pagination Bar */}
|
||||
{totalCount > 0 && (
|
||||
<div className="mt-4 flex items-center justify-between text-xs text-muted-foreground">
|
||||
<div>共 {totalCount} 条记录,当前第 {page} / {totalPages} 页</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Disable confirmation dialog */}
|
||||
<AlertDialog open={togglingUser !== null} onOpenChange={(open) => !open && setTogglingUser(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
确定禁用用户 {togglingUser?.user.display_name ?? togglingUser?.user.username ?? togglingUser?.user.uid}?
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
禁用后该用户的所有有效 Token 将被吊销,且无法再登录平台。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel onClick={() => setTogglingUser(null)}>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-white hover:bg-destructive/90"
|
||||
onClick={() => {
|
||||
if (togglingUser) {
|
||||
void handleStatusToggle(togglingUser.user, false)
|
||||
setTogglingUser(null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
确定禁用
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* User Detail Sheet */}
|
||||
<UserDetailSheet
|
||||
uid={detailUid}
|
||||
onClose={() => setDetailUid(null)}
|
||||
onAssignRoles={() => {
|
||||
const u = usersQuery.data?.data?.find((x) => x.uid === detailUid)
|
||||
if (u) {
|
||||
setAssigningUser(u)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Assign Roles Modal */}
|
||||
{assigningUser && (
|
||||
<AssignRolesModal
|
||||
user={assigningUser}
|
||||
onClose={() => setAssigningUser(null)}
|
||||
onSaved={() => {
|
||||
refresh()
|
||||
setAssigningUser(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AssignRolesModal({
|
||||
user,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
user: PlatformUser
|
||||
onClose: () => void
|
||||
onSaved: () => void
|
||||
}) {
|
||||
const rolesQuery = useQuery({ queryKey: ['roles'], queryFn: fetchRoles })
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set(user.roles ?? []))
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
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 () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await syncUserRoles(user.uid, [...selected])
|
||||
toast.success(`已更新 ${user.display_name ?? user.email ?? user.uid} 的角色`)
|
||||
onSaved()
|
||||
} catch (error) {
|
||||
handleApiError(error)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>分配角色:{user.display_name ?? user.username ?? user.uid}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-2 py-2">
|
||||
{(rolesQuery.data?.data ?? []).map((role) => (
|
||||
<label key={role.name} className="flex items-center gap-2 text-sm cursor-pointer py-1">
|
||||
<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>
|
||||
)
|
||||
}
|
||||
@@ -45,11 +45,6 @@ function LoginPage() {
|
||||
|
||||
const me = await fetchMe()
|
||||
const roles = me.meta?.roles ?? []
|
||||
if (!roles.includes('admin') && !roles.includes('super-admin')) {
|
||||
useAuthStore.getState().clear()
|
||||
toast.error('该账号不是管理员,无法登录管理后台')
|
||||
return
|
||||
}
|
||||
useAuthStore.getState().setSession(me.data, roles, me.meta?.permissions ?? [])
|
||||
|
||||
await navigate({ to: '/' })
|
||||
|
||||
Reference in New Issue
Block a user