安全/鉴权:登出清服务端 httpOnly 令牌、登录 IP 限流前置 bcrypt、停用账号 令牌在 6 个内联 role handler 失效、admin/items 存在性 oracle 认证前置、 同意偏好 sanitize fail-closed、api-crypto 按 HTTP 方法判体。 CMS:workflow 状态更新+审计收进交互式 $transaction(失败即回滚)、编辑器 richtext 走 textarea 防换行损毁、array/object 子字段按作用域读写防污染、 about/contact/erp-upgrade 补 ISR revalidate 与路由映射。 UI/a11y:AnimatedCounter 入视口前显起点、CLS 累计上报、MetricCard 动画入 effect 并卸载取消 rAF、后台状态四态映射/搜索防抖+序号守卫/媒体单 input/ 吞错改横幅/表单 label-aria 关联。 新增对应判别性单测与 pagination/rate-limit/client-ip/sanitize/validate-content-data 等模块及 tests-integration 真库集成层。
558 lines
21 KiB
TypeScript
558 lines
21 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState, useCallback, useRef } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
import { useAuth } from '@/components/admin/auth-context';
|
|
import { adminApi } from '@/lib/admin-api';
|
|
import { toast } from '@/components/ui/sonner';
|
|
import {
|
|
AlertDialog,
|
|
AlertDialogAction,
|
|
AlertDialogCancel,
|
|
AlertDialogContent,
|
|
AlertDialogDescription,
|
|
AlertDialogFooter,
|
|
AlertDialogHeader,
|
|
AlertDialogTitle,
|
|
} from '@/components/ui/alert-dialog';
|
|
import { Plus, Edit, Trash2, Search, UserCog, Shield, Mail, Calendar } from 'lucide-react';
|
|
|
|
interface UserData {
|
|
id: string;
|
|
username: string;
|
|
nickname: string;
|
|
email: string;
|
|
phone: string;
|
|
status: number;
|
|
role: string;
|
|
roles: Array<{ code: string; name: string }>;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
interface RoleData {
|
|
code: string;
|
|
name: string;
|
|
builtin: boolean;
|
|
}
|
|
|
|
const ROLE_LABELS: Record<string, string> = {
|
|
super_admin: '超级管理员',
|
|
content_admin: '内容管理员',
|
|
content_editor: '内容编辑',
|
|
reviewer: '审核员',
|
|
readonly: '只读用户',
|
|
};
|
|
|
|
const ROLE_COLORS: Record<string, string> = {
|
|
super_admin: 'bg-error-bg text-error-text',
|
|
content_admin: 'bg-info-bg text-info-text',
|
|
content_editor: 'bg-success-bg text-success-text',
|
|
reviewer: 'bg-warning-bg text-warning-text',
|
|
readonly: 'bg-bg-hover text-text-secondary',
|
|
};
|
|
|
|
const SEARCH_DEBOUNCE_MS = 300;
|
|
|
|
export default function UsersPage() {
|
|
const { user, loading: authLoading } = useAuth();
|
|
const router = useRouter();
|
|
|
|
const [users, setUsers] = useState<UserData[]>([]);
|
|
const [total, setTotal] = useState(0);
|
|
const [page, setPage] = useState(1);
|
|
const [searchInput, setSearchInput] = useState('');
|
|
const [search, setSearch] = useState('');
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState('');
|
|
const [roles, setRoles] = useState<RoleData[]>([]);
|
|
const pageSize = 20;
|
|
// 单调递增的请求序号:只有最新一次请求的响应可以写进 state
|
|
const fetchSeqRef = useRef(0);
|
|
|
|
// Create/Edit dialog state
|
|
const [dialogOpen, setDialogOpen] = useState(false);
|
|
const [editingUser, setEditingUser] = useState<UserData | null>(null);
|
|
const [formData, setFormData] = useState({
|
|
username: '',
|
|
password: '',
|
|
nickname: '',
|
|
email: '',
|
|
phone: '',
|
|
roleCodes: [] as string[],
|
|
});
|
|
const [saving, setSaving] = useState(false);
|
|
|
|
// Delete dialog state
|
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
|
const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
const timer = setTimeout(() => setSearch(searchInput), SEARCH_DEBOUNCE_MS);
|
|
return () => clearTimeout(timer);
|
|
}, [searchInput]);
|
|
|
|
const fetchUsers = useCallback(async () => {
|
|
const seq = ++fetchSeqRef.current;
|
|
setLoading(true);
|
|
setError('');
|
|
try {
|
|
const query = new URLSearchParams();
|
|
query.set('page', String(page));
|
|
query.set('pageSize', String(pageSize));
|
|
if (search) query.set('search', search);
|
|
|
|
const data = await adminApi.request<{
|
|
users: UserData[];
|
|
total: number;
|
|
page: number;
|
|
pageSize: number;
|
|
totalPages: number;
|
|
}>(`/api/admin/users?${query.toString()}`);
|
|
if (seq !== fetchSeqRef.current) return;
|
|
setUsers(data.users || []);
|
|
setTotal(data.total || 0);
|
|
} catch (err) {
|
|
if (seq !== fetchSeqRef.current) return;
|
|
setError(err instanceof Error ? err.message : '加载失败');
|
|
} finally {
|
|
if (seq === fetchSeqRef.current) setLoading(false);
|
|
}
|
|
}, [page, search]);
|
|
|
|
const fetchRoles = useCallback(async () => {
|
|
try {
|
|
const data = await adminApi.getRoles();
|
|
setRoles(data.roles || []);
|
|
} catch {
|
|
// Roles fetch is secondary
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!authLoading && !user) {
|
|
router.push('/admin/login');
|
|
return;
|
|
}
|
|
if (user) {
|
|
fetchUsers();
|
|
fetchRoles();
|
|
}
|
|
}, [user, authLoading, router, fetchUsers, fetchRoles]);
|
|
|
|
const openCreateDialog = () => {
|
|
setEditingUser(null);
|
|
setFormData({ username: '', password: '', nickname: '', email: '', phone: '', roleCodes: [] });
|
|
setDialogOpen(true);
|
|
};
|
|
|
|
const openEditDialog = (u: UserData) => {
|
|
setEditingUser(u);
|
|
setFormData({
|
|
username: u.username,
|
|
password: '',
|
|
nickname: u.nickname,
|
|
email: u.email,
|
|
phone: u.phone,
|
|
roleCodes: u.roles.map((r) => r.code),
|
|
});
|
|
setDialogOpen(true);
|
|
};
|
|
|
|
const handleSave = async () => {
|
|
if (editingUser) {
|
|
// Update
|
|
if (!formData.nickname && !formData.email) {
|
|
toast.error('请填写昵称或邮箱');
|
|
return;
|
|
}
|
|
setSaving(true);
|
|
try {
|
|
const body: Record<string, unknown> = {
|
|
nickname: formData.nickname,
|
|
email: formData.email,
|
|
phone: formData.phone,
|
|
roleCodes: formData.roleCodes,
|
|
};
|
|
if (formData.password) body.password = formData.password;
|
|
await adminApi.request(`/api/admin/users?id=${editingUser.id}`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify(body),
|
|
});
|
|
toast.success('用户更新成功');
|
|
setDialogOpen(false);
|
|
fetchUsers();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '更新失败');
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
} else {
|
|
// Create
|
|
if (!formData.username || !formData.password) {
|
|
toast.error('用户名和密码必填');
|
|
return;
|
|
}
|
|
if (formData.username.length < 3) {
|
|
toast.error('用户名长度不能少于 3 位');
|
|
return;
|
|
}
|
|
if (formData.password.length < 6) {
|
|
toast.error('密码长度不能少于 6 位');
|
|
return;
|
|
}
|
|
setSaving(true);
|
|
try {
|
|
await adminApi.request('/api/admin/users', {
|
|
method: 'POST',
|
|
body: JSON.stringify(formData),
|
|
});
|
|
toast.success('用户创建成功');
|
|
setDialogOpen(false);
|
|
fetchUsers();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '创建失败');
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
};
|
|
|
|
const handleDelete = async () => {
|
|
if (!pendingDeleteId) return;
|
|
try {
|
|
await adminApi.request(`/api/admin/users?id=${pendingDeleteId}`, { method: 'DELETE' });
|
|
toast.success('用户已删除');
|
|
setDeleteDialogOpen(false);
|
|
setPendingDeleteId(null);
|
|
fetchUsers();
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '删除失败');
|
|
}
|
|
};
|
|
|
|
const toggleRole = (code: string) => {
|
|
setFormData((prev) => ({
|
|
...prev,
|
|
roleCodes: prev.roleCodes.includes(code)
|
|
? prev.roleCodes.filter((r) => r !== code)
|
|
: [...prev.roleCodes, code],
|
|
}));
|
|
};
|
|
|
|
const totalPages = Math.ceil(total / pageSize);
|
|
|
|
if (authLoading || (!user && typeof window !== 'undefined')) {
|
|
return (
|
|
<div className="flex items-center justify-center h-64">
|
|
<div className="animate-spin w-8 h-8 border-2 border-border-dark border-t-transparent rounded-full" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<h1 className="text-xl font-bold text-text-primary">用户管理</h1>
|
|
<p className="text-sm text-text-muted mt-1">管理系统用户与角色分配</p>
|
|
</div>
|
|
<button
|
|
onClick={openCreateDialog}
|
|
className="flex items-center gap-2 px-4 py-2 bg-dark-bg text-white rounded-lg text-sm font-medium hover:bg-dark-bg-secondary transition-colors"
|
|
>
|
|
<Plus className="w-4 h-4" />
|
|
创建用户
|
|
</button>
|
|
</div>
|
|
|
|
{/* Search */}
|
|
<div className="relative">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
|
|
<input
|
|
type="text"
|
|
placeholder="搜索用户名、昵称或邮箱..."
|
|
value={searchInput}
|
|
onChange={(e) => { setSearchInput(e.target.value); setPage(1); }}
|
|
className="w-full pl-10 pr-4 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
|
|
{error && (
|
|
<div className="p-4 bg-error-bg border border-border-secondary rounded-lg text-sm text-error-text">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
{/* Users table */}
|
|
<div className="bg-bg-primary rounded-lg border border-border-primary overflow-hidden">
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-sm">
|
|
<thead>
|
|
<tr className="border-b border-border-primary bg-bg-secondary">
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">用户名</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">昵称</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">邮箱</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">角色</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">状态</th>
|
|
<th className="text-left px-4 py-3 font-medium text-text-tertiary">创建时间</th>
|
|
<th className="text-right px-4 py-3 font-medium text-text-tertiary">操作</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{loading ? (
|
|
<tr>
|
|
<td colSpan={7} className="px-4 py-12 text-center text-text-muted">
|
|
<div className="flex items-center justify-center gap-2">
|
|
<div className="animate-spin w-4 h-4 border-2 border-border-secondary border-t-transparent rounded-full" />
|
|
加载中...
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
) : users.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={7} className="px-4 py-12 text-center text-text-muted">
|
|
暂无用户数据
|
|
</td>
|
|
</tr>
|
|
) : (
|
|
users.map((u) => (
|
|
<tr key={u.id} className="border-b border-border-light hover:bg-bg-secondary">
|
|
<td className="px-4 py-3">
|
|
<div className="flex items-center gap-2">
|
|
<UserCog className="w-4 h-4 text-text-muted" />
|
|
<span className="font-medium text-text-primary">{u.username}</span>
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3 text-text-tertiary">{u.nickname || '-'}</td>
|
|
<td className="px-4 py-3">
|
|
{u.email ? (
|
|
<a href={`mailto:${u.email}`} className="text-text-tertiary hover:text-text-primary flex items-center gap-1">
|
|
<Mail className="w-3 h-3" />
|
|
{u.email}
|
|
</a>
|
|
) : (
|
|
<span className="text-text-muted">-</span>
|
|
)}
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<div className="flex flex-wrap gap-1">
|
|
{u.roles.map((r) => (
|
|
<span
|
|
key={r.code}
|
|
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${
|
|
ROLE_COLORS[r.code] || 'bg-bg-hover text-text-secondary'
|
|
}`}
|
|
>
|
|
<Shield className="w-3 h-3" />
|
|
{r.name || ROLE_LABELS[r.code] || r.code}
|
|
</span>
|
|
))}
|
|
{u.roles.length === 0 && (
|
|
<span className="text-xs text-text-muted">无角色</span>
|
|
)}
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<span
|
|
className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
|
|
u.status === 1
|
|
? 'bg-success-bg text-success-text'
|
|
: 'bg-error-bg text-error-text'
|
|
}`}
|
|
>
|
|
{u.status === 1 ? '启用' : '禁用'}
|
|
</span>
|
|
</td>
|
|
<td className="px-4 py-3 text-text-muted text-xs">
|
|
<div className="flex items-center gap-1">
|
|
<Calendar className="w-3 h-3" />
|
|
{new Date(u.createdAt).toLocaleDateString('zh-CN')}
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3 text-right">
|
|
<div className="flex items-center justify-end gap-1">
|
|
<button
|
|
onClick={() => openEditDialog(u)}
|
|
className="p-1.5 rounded hover:bg-bg-hover text-text-muted hover:text-text-secondary"
|
|
title="编辑"
|
|
>
|
|
<Edit className="w-4 h-4" />
|
|
</button>
|
|
<button
|
|
onClick={() => { setPendingDeleteId(u.id); setDeleteDialogOpen(true); }}
|
|
className="p-1.5 rounded hover:bg-error-bg text-text-muted hover:text-error-text"
|
|
title="删除"
|
|
>
|
|
<Trash2 className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
{/* Pagination */}
|
|
{totalPages > 1 && (
|
|
<div className="flex items-center justify-between px-4 py-3 border-t border-border-primary bg-bg-secondary">
|
|
<span className="text-sm text-text-muted">
|
|
共 {total} 条,第 {page}/{totalPages} 页
|
|
</span>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
|
disabled={page <= 1}
|
|
className="px-3 py-1.5 text-sm rounded border border-border-primary hover:bg-bg-hover disabled:opacity-50 disabled:cursor-not-allowed"
|
|
>
|
|
上一页
|
|
</button>
|
|
<button
|
|
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
|
disabled={page >= totalPages}
|
|
className="px-3 py-1.5 text-sm rounded border border-border-primary hover:bg-bg-hover disabled:opacity-50 disabled:cursor-not-allowed"
|
|
>
|
|
下一页
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Create/Edit Dialog */}
|
|
{dialogOpen && (
|
|
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
|
<div className="fixed inset-0 bg-overlay/50" onClick={() => setDialogOpen(false)} />
|
|
<div className="relative bg-bg-primary rounded-lg shadow-xl w-full max-w-md mx-4 p-6">
|
|
<h2 className="text-lg font-bold text-text-primary mb-4">
|
|
{editingUser ? '编辑用户' : '创建用户'}
|
|
</h2>
|
|
|
|
<div className="space-y-4">
|
|
<div>
|
|
<label htmlFor="admin-user-username" className="block text-sm font-medium text-text-secondary mb-1">用户名</label>
|
|
<input
|
|
id="admin-user-username"
|
|
type="text"
|
|
value={formData.username}
|
|
onChange={(e) => setFormData((p) => ({ ...p, username: e.target.value }))}
|
|
disabled={!!editingUser}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary disabled:bg-bg-hover disabled:text-text-muted"
|
|
placeholder="3-32 位字母/数字/下划线"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label htmlFor="admin-user-password" className="block text-sm font-medium text-text-secondary mb-1">
|
|
{editingUser ? '新密码(留空不修改)' : '密码'}
|
|
</label>
|
|
<input
|
|
id="admin-user-password"
|
|
type="password"
|
|
value={formData.password}
|
|
onChange={(e) => setFormData((p) => ({ ...p, password: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
placeholder={editingUser ? '留空保持原密码' : '至少 6 位'}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label htmlFor="admin-user-nickname" className="block text-sm font-medium text-text-secondary mb-1">昵称</label>
|
|
<input
|
|
id="admin-user-nickname"
|
|
type="text"
|
|
value={formData.nickname}
|
|
onChange={(e) => setFormData((p) => ({ ...p, nickname: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label htmlFor="admin-user-email" className="block text-sm font-medium text-text-secondary mb-1">邮箱</label>
|
|
<input
|
|
id="admin-user-email"
|
|
type="email"
|
|
value={formData.email}
|
|
onChange={(e) => setFormData((p) => ({ ...p, email: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label htmlFor="admin-user-phone" className="block text-sm font-medium text-text-secondary mb-1">手机号</label>
|
|
<input
|
|
id="admin-user-phone"
|
|
type="tel"
|
|
value={formData.phone}
|
|
onChange={(e) => setFormData((p) => ({ ...p, phone: e.target.value }))}
|
|
className="w-full px-3 py-2 border border-border-primary rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-border-primary"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<span id="admin-user-roles-label" className="block text-sm font-medium text-text-secondary mb-2">角色分配</span>
|
|
<div className="flex flex-wrap gap-2" role="group" aria-labelledby="admin-user-roles-label">
|
|
{roles.map((r) => (
|
|
<button
|
|
key={r.code}
|
|
type="button"
|
|
onClick={() => toggleRole(r.code)}
|
|
className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
|
|
formData.roleCodes.includes(r.code)
|
|
? 'bg-dark-bg text-white border-border-dark'
|
|
: 'bg-bg-primary text-text-tertiary border-border-primary hover:border-border-secondary'
|
|
}`}
|
|
>
|
|
{r.name}
|
|
</button>
|
|
))}
|
|
{roles.length === 0 && (
|
|
<span className="text-xs text-text-muted">加载角色中...</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-end gap-3 mt-6 pt-4 border-t border-border-light">
|
|
<button
|
|
onClick={() => setDialogOpen(false)}
|
|
className="px-4 py-2 text-sm text-text-tertiary hover:text-text-primary"
|
|
>
|
|
取消
|
|
</button>
|
|
<button
|
|
onClick={handleSave}
|
|
disabled={saving}
|
|
className="flex items-center gap-2 px-4 py-2 bg-dark-bg text-white rounded-lg text-sm font-medium hover:bg-dark-bg-secondary disabled:opacity-50 transition-colors"
|
|
>
|
|
{saving && <div className="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full" />}
|
|
{editingUser ? '保存更改' : '创建用户'}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Delete confirmation */}
|
|
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
|
<AlertDialogContent>
|
|
<AlertDialogHeader>
|
|
<AlertDialogTitle>确认删除</AlertDialogTitle>
|
|
<AlertDialogDescription>
|
|
删除后该用户将无法登录系统,此操作不可撤销。
|
|
</AlertDialogDescription>
|
|
</AlertDialogHeader>
|
|
<AlertDialogFooter>
|
|
<AlertDialogCancel>取消</AlertDialogCancel>
|
|
<AlertDialogAction onClick={handleDelete} className="bg-error hover:bg-error-hover">
|
|
确认删除
|
|
</AlertDialogAction>
|
|
</AlertDialogFooter>
|
|
</AlertDialogContent>
|
|
</AlertDialog>
|
|
</div>
|
|
);
|
|
} |