feat: opsx-loki 全面升级 — 前端重构/用户与LDAP/部署向导/日志查询
基于 WEB-UI-Development-Guide 标准的整体升级,并更名 LokiDeploy → opsx-loki。 前端(Gin+React+shadcn/ui): - 按 02/07 章重构:页面域化拆分(无超 400 行文件)、PageContainer/ListQuery、 反馈分级(成功静默/失败 toast/危险确认)、401 单飞刷新+队列重放 - 暗色模式(next-themes)+ 语义 Token(--primary 品牌色/success/warning/info) - 部署向导(状态推导四步:环境→存储→Loki→采集,内嵌表单闭环) - 日志查询页:LogQL 标签构建器/拖拽直方图/日志上下文/Live Tail/查询历史 - 按用户+标签策略的查询授权(服务端强制合并策略) 后端(Go+Gin+JSON DB): - 简单用户管理(仅 admin,无 RBAC)+ TokenVersion 会话吊销 + 登录 IP 限流 - LDAP 接入:配置(AES 加密存储/hasPassword 脱敏)/测试连接/批量导入/登录 - 存储配置测试连接(SigV4 零依赖)+ 桶不存在自动创建 - Loki 三模式部署修复:SSH 密钥认证、3.x 配置模板、ruler 对象存储嵌套块、 凭证解密、孤儿 deploying 状态恢复、Grafana 部署(可选默认关)+面板导入 - DaemonSet 采集纯 YAML(去 helm 依赖)+ DNS 自愈回退 ClusterIP + 集群名标签 - 日志查询代理:cluster-svc 经 kube-apiserver proxy/url 直连 + cursor 翻页 - 统一 log 命名空间;部署就绪探活;Grafana 访问地址自动记录 修复:run.sh 增量编译检测、Sanitized 脱敏补全、LokiDeployment Update 白名单、 健康检查 CreatedAt 零值等 10+ 存量 bug。 数据兼容:DB 沿用旧 lokideploy.json(新名优先);localStorage 一次性迁移; HKDF 加密前缀保留(已加密凭证不受影响)。
This commit is contained in:
1 parent
327e282356
commit
f9c6c1d826
204 files changed
+14107
-9103
No files matched your search
@@ -0,0 +1,203 @@
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { Users, RefreshCw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { ldapApi, type LdapUserPreview, type LdapImportResult } from '@/api/ldap'
|
||||
import { toast } from 'sonner'
|
||||
import type { User } from '@/types'
|
||||
|
||||
interface LdapImportDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** 本地用户列表(用于标记已导入,禁选) */
|
||||
localUsers: User[]
|
||||
onImported: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 LDAP 导入用户弹窗 — 打开即拉取 LDAP 用户列表;
|
||||
* 已导入(LDAP 来源)置灰禁选;本地同名用户标注「将转为 LDAP」。
|
||||
*/
|
||||
export const LdapImportDialog = memo(function LdapImportDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
localUsers,
|
||||
onImported,
|
||||
}: LdapImportDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [users, setUsers] = useState<LdapUserPreview[]>([])
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [result, setResult] = useState<LdapImportResult | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const localMap = useMemo(() => {
|
||||
const m = new Map<string, User>()
|
||||
localUsers.forEach((u) => m.set(u.username, u))
|
||||
return m
|
||||
}, [localUsers])
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setResult(null)
|
||||
try {
|
||||
const list = await ldapApi.listUsers()
|
||||
setUsers(list)
|
||||
setSelected(new Set())
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : '加载 LDAP 用户失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (open) void loadUsers()
|
||||
}, [open, loadUsers])
|
||||
|
||||
const toggle = (username: string, disabled: boolean) => {
|
||||
if (disabled) return
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(username)) next.delete(username)
|
||||
else next.add(username)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleImport = async () => {
|
||||
const picked = users.filter((u) => selected.has(u.username))
|
||||
if (picked.length === 0) return
|
||||
setImporting(true)
|
||||
try {
|
||||
const r = await ldapApi.batchImport(
|
||||
picked.map((u) => ({
|
||||
dn: u.dn, username: u.username, nickname: u.displayName, email: u.email,
|
||||
}))
|
||||
)
|
||||
setResult(r)
|
||||
onImported()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '导入失败')
|
||||
} finally {
|
||||
setImporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>从 LDAP 导入用户</DialogTitle>
|
||||
<DialogDescription>
|
||||
来自 LDAP 目录的用户;导入后使用 LDAP 密码登录,角色为普通用户
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{result ? (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-4 text-sm">
|
||||
{result.successCount > 0 && (
|
||||
<span className="text-success">新增 {result.successCount}</span>
|
||||
)}
|
||||
{result.updatedCount > 0 && <span className="text-info">转为 LDAP {result.updatedCount}</span>}
|
||||
{result.skippedCount > 0 && <span className="text-muted-foreground">跳过 {result.skippedCount}</span>}
|
||||
{result.failedCount > 0 && <span className="text-destructive">失败 {result.failedCount}</span>}
|
||||
</div>
|
||||
{result.failedUsers.length > 0 && (
|
||||
<div className="text-xs text-destructive space-y-1 max-h-32 overflow-y-auto">
|
||||
{result.failedUsers.map((f) => (
|
||||
<p key={f.username}>{f.username}:{f.error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => void loadUsers()}>继续导入</Button>
|
||||
<Button onClick={() => onOpenChange(false)}>完成</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{loading ? '加载 LDAP 用户…' : `共 ${users.length} 个用户,已选 ${selected.size} 个`}
|
||||
</p>
|
||||
<Button variant="ghost" size="sm" onClick={() => void loadUsers()} disabled={loading}>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
</div>
|
||||
{error ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
请到
|
||||
<Link to="/settings" className="text-primary mx-1">系统设置</Link>
|
||||
检查 LDAP 配置与启用状态
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="h-72 rounded-lg border border-border">
|
||||
<div className="divide-y divide-border">
|
||||
{users.map((u) => {
|
||||
const local = localMap.get(u.username)
|
||||
const isLdapAlready = local?.['authSource'] === 'ldap'
|
||||
const willConvert = !!local && !isLdapAlready
|
||||
const disabled = isLdapAlready
|
||||
const checked = selected.has(u.username)
|
||||
return (
|
||||
<label
|
||||
key={u.dn}
|
||||
className={`flex items-center gap-3 px-3 py-2.5 ${disabled ? 'opacity-50' : 'cursor-pointer hover:bg-muted/50'}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onCheckedChange={() => toggle(u.username, disabled)}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">{u.username}</span>
|
||||
{isLdapAlready && (
|
||||
<span className="text-xs text-muted-foreground">已导入</span>
|
||||
)}
|
||||
{willConvert && (
|
||||
<span className="text-xs text-info">本地同名,将转为 LDAP</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{u.displayName || '无姓名'} · {u.email || '无邮箱'}
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
{!loading && users.length === 0 && (
|
||||
<div className="flex items-center justify-center gap-2 py-10 text-muted-foreground text-sm">
|
||||
<Users className="w-4 h-4" /> 目录下没有用户
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
|
||||
<Button onClick={handleImport} disabled={importing || selected.size === 0}>
|
||||
{importing ? '导入中...' : `导入 ${selected.size} 个用户`}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { Dice5 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { PasswordInput } from '@/components/PasswordInput'
|
||||
import { userApi } from '@/api'
|
||||
import { toast } from 'sonner'
|
||||
import type { User } from '@/types'
|
||||
|
||||
// 随机密码:12 位,大小写字母 + 数字,满足后端 min=6
|
||||
function randomPassword(): string {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
|
||||
let pwd = ''
|
||||
const array = new Uint32Array(12)
|
||||
crypto.getRandomValues(array)
|
||||
for (let i = 0; i < 12; i++) {
|
||||
pwd += chars[array[i] % chars.length]
|
||||
}
|
||||
return pwd
|
||||
}
|
||||
|
||||
interface ResetPasswordDialogProps {
|
||||
user: User | null
|
||||
onClose: () => void
|
||||
/** 重置成功回调(提示信息由调用方决定) */
|
||||
onReset: () => void
|
||||
}
|
||||
|
||||
/** 管理员重置密码弹窗 — 重置后目标用户全部旧会话立即失效(后端递增 TokenVersion) */
|
||||
export const ResetPasswordDialog = memo(function ResetPasswordDialog({
|
||||
user,
|
||||
onClose,
|
||||
onReset,
|
||||
}: ResetPasswordDialogProps) {
|
||||
const [password, setPassword] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setPassword('')
|
||||
setError('')
|
||||
}
|
||||
}, [user])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (password.length < 6) {
|
||||
setError('密码至少需要 6 位')
|
||||
return
|
||||
}
|
||||
if (!user) return
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await userApi.resetPassword(user.id, password)
|
||||
onClose()
|
||||
onReset()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '重置密码失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={user !== null} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>重置密码</DialogTitle>
|
||||
<DialogDescription>
|
||||
重置「{user?.username}」的密码后,该用户的所有登录会话将立即失效。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reset-password">新密码 *</Label>
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
id="reset-password"
|
||||
className="flex-1"
|
||||
placeholder="至少 6 位"
|
||||
value={password}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value)
|
||||
setError('')
|
||||
}}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
aria-label="随机生成密码"
|
||||
title="随机生成密码"
|
||||
onClick={() => {
|
||||
setPassword(randomPassword())
|
||||
setError('')
|
||||
}}
|
||||
>
|
||||
<Dice5 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={submitting}>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="submit" disabled={submitting || password.length < 6}>
|
||||
{submitting ? '重置中...' : '重置密码'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,174 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { PasswordInput } from '@/components/PasswordInput'
|
||||
import { userApi } from '@/api'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const userFormSchema = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.min(2, '用户名至少 2 个字符')
|
||||
.max(32, '用户名最多 32 个字符'),
|
||||
nickname: z.string().optional(),
|
||||
password: z.string().min(6, '密码至少需要 6 位'),
|
||||
role: z.enum(['admin', 'user']),
|
||||
})
|
||||
|
||||
export type UserFormValues = z.infer<typeof userFormSchema>
|
||||
|
||||
const DEFAULT_VALUES: UserFormValues = {
|
||||
username: '',
|
||||
nickname: '',
|
||||
password: '',
|
||||
role: 'user',
|
||||
}
|
||||
|
||||
interface UserFormDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onCreated: () => void
|
||||
}
|
||||
|
||||
/** 创建用户弹窗 — admin 专用,RHF + zod */
|
||||
export const UserFormDialog = memo(function UserFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onCreated,
|
||||
}: UserFormDialogProps) {
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const form = useForm<UserFormValues>({
|
||||
resolver: zodResolver(userFormSchema),
|
||||
defaultValues: DEFAULT_VALUES,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset(DEFAULT_VALUES)
|
||||
}
|
||||
}, [open, form])
|
||||
|
||||
const onSubmit = form.handleSubmit(async (values) => {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await userApi.create({
|
||||
username: values.username,
|
||||
nickname: values.nickname || undefined,
|
||||
password: values.password,
|
||||
role: values.role,
|
||||
})
|
||||
onOpenChange(false)
|
||||
onCreated()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '创建用户失败')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>创建用户</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="username"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>用户名 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="登录用户名" autoComplete="off" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="nickname"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>昵称</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="显示昵称(可选)" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>初始密码 *</FormLabel>
|
||||
<FormControl>
|
||||
<PasswordInput
|
||||
placeholder="至少 6 位"
|
||||
autoComplete="new-password"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="role"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>角色 *</FormLabel>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择角色" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="user">普通用户</SelectItem>
|
||||
<SelectItem value="admin">管理员</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit" className="w-full" disabled={submitting}>
|
||||
{submitting ? '创建中...' : '创建用户'}
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
import { memo, useCallback, useEffect, useState } from 'react'
|
||||
import { Users, UserRound, UsersRound, Plus, KeyRound, Trash2, ShieldCheck } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { userApi } from '@/api'
|
||||
import { PageContainer } from '@/components/PageContainer'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { EmptyState } from '@/components/EmptyState'
|
||||
import { ErrorState } from '@/components/ErrorState'
|
||||
import { ConfirmDialog } from '@/components/ConfirmDialog'
|
||||
import { useListQuery } from '@/hooks/useListQuery'
|
||||
import { ldapApi, type LdapConfig } from '@/api/ldap'
|
||||
import { LdapImportDialog } from './components/LdapImportDialog'
|
||||
import { getUser } from '@/lib/auth-storage'
|
||||
import { toast } from 'sonner'
|
||||
import type { User } from '@/types'
|
||||
import { UserFormDialog } from './components/UserFormDialog'
|
||||
import { ResetPasswordDialog } from './components/ResetPasswordDialog'
|
||||
|
||||
/** 角色徽章 */
|
||||
function SourceBadge({ source }: { source?: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-full bg-info/10 text-info text-xs font-medium">
|
||||
{source === 'ldap' ? 'LDAP 导入' : '本地账号'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function RoleBadge({ role }: { role: string }) {
|
||||
return role === 'admin' ? (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-success/10 text-success text-xs font-medium">
|
||||
<ShieldCheck className="w-3 h-3" />
|
||||
管理员
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-muted text-muted-foreground text-xs font-medium">
|
||||
普通用户
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户管理页(admin 专用,无 RBAC — 用户仅 admin/user 两级)
|
||||
* - 非 admin 直访时显示权限提示空态(后端 AdminAuth 403 兜底)
|
||||
* - 单卡片行列表 + 创建/重置密码/删除;成功操作静默(反馈分级)
|
||||
*/
|
||||
const UsersPage = memo(function UsersPage() {
|
||||
const currentUser = getUser()
|
||||
const isAdmin = currentUser?.role === 'admin'
|
||||
|
||||
const query = useListQuery<User>((params, signal) =>
|
||||
userApi.list(params, { signal })
|
||||
)
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [ldapImportOpen, setLdapImportOpen] = useState(false)
|
||||
// LDAP 已启用且配置齐全才显示「从 LDAP 导入」(用户要求的联动)
|
||||
const [ldapReady, setLdapReady] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
ldapApi
|
||||
.getConfig()
|
||||
.then((c: LdapConfig) => setLdapReady(!!(c.enabled && c.configured)))
|
||||
.catch(() => setLdapReady(false))
|
||||
}, [])
|
||||
const [resetTarget, setResetTarget] = useState<User | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<User | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
const id = deleteTarget?.id
|
||||
if (!id) return
|
||||
setDeleting(true)
|
||||
try {
|
||||
await userApi.remove(id)
|
||||
setDeleteTarget(null)
|
||||
query.refresh()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : '删除用户失败')
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}, [deleteTarget, query])
|
||||
|
||||
// 非管理员:菜单不可见,直访时给明确提示
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<PageContainer title="用户管理">
|
||||
<EmptyState
|
||||
icon={UserRound}
|
||||
title="需要管理员权限"
|
||||
description="用户管理仅管理员可用,请联系管理员处理账号事宜"
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PageContainer
|
||||
title="用户管理"
|
||||
description="管理平台登录账号(仅管理员)"
|
||||
action={
|
||||
<div className="flex items-center gap-2">
|
||||
{ldapReady && (
|
||||
<Button variant="outline" onClick={() => setLdapImportOpen(true)}>
|
||||
<UsersRound className="w-4 h-4 mr-1" />
|
||||
从 LDAP 导入
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => setFormOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
创建用户
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{query.loading ? (
|
||||
<LoadingSpinner className="h-64" />
|
||||
) : query.error ? (
|
||||
<ErrorState message={query.error} onRetry={query.refresh} />
|
||||
) : query.list.length === 0 ? (
|
||||
<EmptyState icon={Users} title="暂无用户" description="创建第一个用户账号" />
|
||||
) : (
|
||||
<Card className="border-border">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Users className="w-4 h-4" />
|
||||
用户列表(共 {query.total} 个)
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="divide-y divide-border">
|
||||
{query.list.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0"
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="w-9 h-9 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
|
||||
<UserRound className="w-4 h-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium truncate">{user.username}</span>
|
||||
<RoleBadge role={user.role} />
|
||||
<SourceBadge source={user.authSource} />
|
||||
{user.id === currentUser?.id && (
|
||||
<span className="text-xs text-muted-foreground">(当前登录)</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate mt-0.5">
|
||||
{user.nickname || '未设置昵称'}
|
||||
{user.createdAt &&
|
||||
` · 创建于 ${new Date(user.createdAt).toLocaleDateString()}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{user.authSource !== 'ldap' && (
|
||||
<Button variant="outline" size="sm" onClick={() => setResetTarget(user)}>
|
||||
<KeyRound className="w-3.5 h-3.5 mr-1" />
|
||||
重置密码
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label={`删除用户 ${user.username}`}
|
||||
className="text-destructive hover:bg-destructive/10"
|
||||
disabled={user.id === currentUser?.id}
|
||||
title={
|
||||
user.id === currentUser?.id ? '不能删除当前登录账号' : undefined
|
||||
}
|
||||
onClick={() => setDeleteTarget(user)}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<UserFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={setFormOpen}
|
||||
onCreated={query.reload}
|
||||
/>
|
||||
|
||||
<LdapImportDialog
|
||||
open={ldapImportOpen}
|
||||
onOpenChange={setLdapImportOpen}
|
||||
localUsers={query.list}
|
||||
onImported={query.refresh}
|
||||
/>
|
||||
|
||||
<ResetPasswordDialog
|
||||
key={resetTarget?.id ?? 'none'}
|
||||
user={resetTarget}
|
||||
onClose={() => setResetTarget(null)}
|
||||
onReset={() => {
|
||||
toast.info(`已重置「${resetTarget?.username}」的密码,其所有会话已失效`)
|
||||
setResetTarget(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleteTarget(null)
|
||||
}}
|
||||
name={deleteTarget?.username}
|
||||
title="确认删除用户"
|
||||
onConfirm={handleDelete}
|
||||
loading={deleting}
|
||||
/>
|
||||
</PageContainer>
|
||||
)
|
||||
})
|
||||
|
||||
export default UsersPage
|
||||
Reference in new issue
Block a user