feat: 实现完整的板块级RBAC内容审核系统

- 新增站长/超级管理员/管理员/板块管理员四级角色体系
- 实现实时权限快照加载与细粒度权限校验
- 新增内容审核队列与前后端页面
- 重构用户权限管理与站点管理逻辑
- 新增评论/帖子审核状态与通知推送
- 优化前端权限控制与角色徽章展示
- 修正数据库迁移与默认值问题
This commit is contained in:
2026-09-15 04:47:34 +08:00
parent 6da4309453
commit a7b6421840
44 changed files with 3149 additions and 585 deletions

View File

@@ -6,12 +6,15 @@ import Link from "next/link";
import { Trash2, MessagesSquare, ChevronRight, ChevronDown } from "lucide-react";
import ReactMarkdown from "react-markdown";
import { apiCreateComment, apiDeleteComment, type CommentNode, type User } from "@/lib/api";
import { canModerateBoard } from "@/lib/roles";
import { toast } from "@/lib/toast";
import Avatar from "./Avatar";
import Pagination from "./Pagination";
interface CommentSectionProps {
postId: string;
/** 帖子所属板块:板块管理员仅可管理授权板块的评论 */
boardId: number;
comments: CommentNode[];
total: number; // 楼层数(主评论数)→ 分页与楼层号计算
totalComments: number; // 全部评论数(含回复)→ 头部徽标
@@ -31,6 +34,7 @@ function countReplies(node: CommentNode): number {
export default function CommentSection({
postId,
boardId,
comments,
total,
totalComments,
@@ -58,8 +62,12 @@ export default function CommentSection({
const res = await apiCreateComment(postId, content);
if (res.comment) {
setContent("");
// 新楼层在最后一页:刷新后由服务端直出最新分页
router.refresh();
if (res.comment.status === "pending") {
toast("已提交,等待审核通过后公开");
} else {
// 新楼层在最后一页:刷新后由服务端直出最新分页
router.refresh();
}
} else if (res.error === "未登录") {
router.push(`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`);
} else {
@@ -81,8 +89,12 @@ export default function CommentSection({
if (res.comment) {
setReplyTarget(null);
setReplyContent("");
// 刷新后由 SSR 直出新树(子评论全量挂在本楼)
router.refresh();
if (res.comment.status === "pending") {
toast("已提交,等待审核通过后公开");
} else {
// 刷新后由 SSR 直出新树(子评论全量挂在本楼)
router.refresh();
}
} else if (res.error === "未登录") {
router.push(`/login?redirect=${encodeURIComponent(`/post/${postId}`)}`);
} else {
@@ -122,7 +134,7 @@ export default function CommentSection({
// 引用功能已移除:与"回复"功能重叠,且会割裂讨论上下文(抖音风格无此功能)
const canDelete = (comment: CommentNode) =>
user && (user.id === comment.user.id || user.role === "admin");
!!user && (user.id === comment.user.id || canModerateBoard(user, boardId));
const openReply = (c: CommentNode) => {
setReplyTarget({ id: c.id, nickname: c.user.nickname || c.user.username });

View File

@@ -22,6 +22,7 @@ import {
} from "lucide-react";
import { apiLogout, apiMe, type User } from "@/lib/api";
import { hasAuthCookieHint } from "@/lib/cookies";
import { isStaff } from "@/lib/roles";
import { onUserUpdate, onForceLogout } from "@/lib/userEvents";
import NotificationBell from "./NotificationBell";
import Avatar from "./Avatar";
@@ -294,7 +295,7 @@ export default function Header({
</MobileLink>
)}
{user && <MobileLink href="/settings">账号设置</MobileLink>}
{user?.role === "admin" && (
{user && isStaff(user.role) && (
<MobileLink href="/admin">
<span className="inline-flex items-center gap-2"><ShieldCheck size={15} /> 管理面板</span>
</MobileLink>
@@ -456,7 +457,7 @@ function UserMenu({ user, onLogout }: { user: User; onLogout: () => void }) {
<Settings size={15} style={{ color: "var(--ink-3)" }} /> 账号设置
</Link>
</div>
{user.role === "admin" && (
{isStaff(user.role) && (
<div className="p-1.5" style={{ borderTop: "1px solid var(--line)" }}>
<Link href="/admin" onClick={() => setOpen(false)} className={itemCls} role="menuitem">
<ShieldCheck size={15} style={{ color: "var(--accent)" }} /> 管理面板

View File

@@ -3,7 +3,7 @@
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Bell, CheckCheck, Heart, MessageCircle } from "lucide-react";
import { Bell, CheckCheck, Heart, MessageCircle, CheckCircle2, XCircle } from "lucide-react";
import {
apiFetchNotifications,
apiUnreadCount,
@@ -107,9 +107,23 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
const actionText = (n: NotificationItem) => {
if (n.type === "comment") return "评论了你的帖子";
if (n.type === "reply") return "回复了你的评论";
if (n.type === "approved") return "审核通过";
if (n.type === "rejected") return "未通过审核";
return "点赞了你的帖子";
};
// 审核结果类通知:无互动对象语义,使用专用图标与语义色
const isApproval = (n: NotificationItem) => n.type === "approved" || n.type === "rejected";
const iconStyle = (n: NotificationItem): { color: string; bg: string; node: React.ReactNode } => {
if (n.type === "approved")
return { color: "var(--ok)", bg: "var(--ok-soft)", node: <CheckCircle2 size={15} /> };
if (n.type === "rejected")
return { color: "var(--danger)", bg: "var(--danger-soft)", node: <XCircle size={15} /> };
if (n.type === "like")
return { color: "var(--clay)", bg: "var(--clay-soft)", node: <Heart size={15} /> };
return { color: "var(--accent)", bg: "var(--accent-soft)", node: <MessageCircle size={15} /> };
};
return (
<div className="relative" ref={dropdownRef}>
<button
@@ -171,7 +185,10 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
<p className="meta">还没有通知</p>
</div>
) : (
notifications.map((n) => (
notifications.map((n) => {
const ic = iconStyle(n);
const approval = isApproval(n);
return (
<button
key={n.id}
onClick={() => handleClickNotification(n)}
@@ -184,18 +201,25 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
>
<span
className="w-9 h-9 shrink-0 rounded-full flex items-center justify-center"
style={{
color: n.type === "like" ? "var(--clay)" : "var(--accent)",
background:
n.type === "like" ? "var(--clay-soft)" : "var(--accent-soft)",
}}
style={{ color: ic.color, background: ic.bg }}
>
{n.type === "like" ? <Heart size={15} /> : <MessageCircle size={15} />}
{ic.node}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm leading-snug" style={{ color: "var(--ink)" }}>
<span className="font-medium">{n.actor.nickname}</span>{" "}
<span className="meta">{actionText(n)}</span>
{approval ? (
<span
className="font-bold"
style={{ color: n.type === "approved" ? "var(--ok)" : "var(--danger)" }}
>
{actionText(n)}
</span>
) : (
<>
<span className="font-medium">{n.actor.nickname}</span>{" "}
<span className="meta">{actionText(n)}</span>
</>
)}
</p>
<p className="text-xs mt-1 truncate" style={{ color: "var(--ink-2)" }}>
《{n.post.title}》
@@ -214,7 +238,8 @@ export default function NotificationBell({ initialUnread = 0 }: { initialUnread?
/>
)}
</button>
))
);
})
)}
</div>

View File

@@ -3,18 +3,20 @@
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Pencil, Trash2, Pin, Star, SlidersHorizontal, ChevronDown, Check } from "lucide-react";
import { Pencil, Trash2, Pin, Star, SlidersHorizontal, ChevronDown, Check, Loader2, X } from "lucide-react";
import { apiMe, apiDeletePost, apiTogglePin, apiToggleRecommend, type User } from "@/lib/api";
import { canModerateBoard, isAdminOrAbove } from "@/lib/roles";
import { toast } from "@/lib/toast";
interface PostActionsProps {
postId: string;
authorId: number;
boardId: number;
pinned: number;
recommended: boolean;
}
export default function PostActions({ postId, authorId, pinned, recommended }: PostActionsProps) {
export default function PostActions({ postId, authorId, boardId, pinned, recommended }: PostActionsProps) {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [open, setOpen] = useState(false);
@@ -22,6 +24,7 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
const [isPinned, setIsPinned] = useState(pinned > 0);
const [isRecommended, setIsRecommended] = useState(recommended);
const [acting, setActing] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -47,16 +50,16 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
};
}, [open]);
const canManage = user && (user.id === authorId || user.role === "admin");
const isAdmin = user?.role === "admin";
// 作者本人或有该板块审核权的管理团队可管理;置顶/加精仅管理员及以上
const canManage = !!user && (user.id === authorId || canModerateBoard(user, boardId));
const isAdmin = !!user && isAdminOrAbove(user.role);
const handleDelete = async () => {
setOpen(false);
if (!confirm("确定要删除这篇帖子吗?此操作不可恢复。")) return;
setDeleting(true);
try {
const res = await apiDeletePost(postId);
if (res.message) {
setConfirmDelete(false);
router.push("/");
toast("帖子已删除", "ok");
} else {
@@ -172,7 +175,10 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
<button
type="button"
role="menuitem"
onClick={handleDelete}
onClick={() => {
setOpen(false);
setConfirmDelete(true);
}}
disabled={deleting}
className={`${itemCls} items-center`}
style={{ color: "var(--danger)" }}
@@ -182,6 +188,59 @@ export default function PostActions({ postId, authorId, pinned, recommended }: P
</button>
</div>
)}
{confirmDelete && (
<div
className="fixed inset-0 z-[1000] flex items-center justify-center p-4"
style={{ background: "color-mix(in srgb, var(--ink) 55%, transparent)" }}
onClick={() => !deleting && setConfirmDelete(false)}
>
<div
className="j13-toast-in panel w-full max-w-[400px] rounded-2xl p-6"
style={{ boxShadow: "var(--shadow-lg)" }}
onClick={(e) => e.stopPropagation()}
role="dialog"
aria-modal="true"
>
<div className="flex items-start gap-4">
<span
className="w-12 h-12 rounded-full flex items-center justify-center shrink-0"
style={{ background: "var(--danger-soft)", color: "var(--danger)" }}
aria-hidden="true"
>
<Trash2 size={22} />
</span>
<div className="min-w-0 flex-1">
<h3 className="text-[16px] font-extrabold tracking-tight" style={{ color: "var(--ink)" }}>
删除帖子
</h3>
<p className="meta mt-1.5 text-[13px] leading-relaxed">
确定要删除这篇帖子吗?此操作不可恢复。
</p>
</div>
</div>
<div className="flex items-center justify-end gap-2 mt-5">
<button
type="button"
className="btn btn-line"
onClick={() => setConfirmDelete(false)}
disabled={deleting}
>
<X size={14} /> 取消
</button>
<button
type="button"
className="btn btn-danger"
onClick={handleDelete}
disabled={deleting}
>
{deleting && <Loader2 size={15} className="animate-spin" />}
确认删除
</button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,70 @@
"use client";
import { Crown, BadgeCheck, ShieldCheck, Shield, Users, type LucideIcon } from "lucide-react";
import { roleMeta, type RoleIconKey } from "@/lib/roles";
// 角色图标集中映射(图标库不含 ShieldStar,超管使用 BadgeCheck 表达"全权限认证")
const ICONS: Record<RoleIconKey, LucideIcon> = {
crown: Crown,
"shield-star": BadgeCheck,
shield: ShieldCheck,
"shield-board": Shield,
user: Users,
};
/**
* 角色徽章:图标 + 文案,配色走角色元数据中的 CSS token。
* - board_admin 额外展示授权板块数(或板块名)
* - variant=plain 时仅图标+文字不着底色(用于表头/文本行)
*/
export default function RoleBadge({
role,
boardIds,
boardNames,
size = 11,
className = "",
title,
truncate = false,
}: {
role?: string | null;
boardIds?: number[] | null;
/** id -> 名称映射;提供时板块管理员展示板块名(多选时折叠为 N 个板块) */
boardNames?: Map<number, string> | Record<number, string>;
size?: number;
className?: string;
title?: string;
/** 窄列场景:限制最大宽度并省略过长文案 */
truncate?: boolean;
}) {
const meta = roleMeta(role);
const Icon = ICONS[meta.icon];
let label = meta.label;
if (role === "board_admin") {
if (boardNames) {
const names = (boardIds ?? [])
.map((id) => (boardNames instanceof Map ? boardNames.get(id) : boardNames[id]))
.filter(Boolean) as string[];
if (names.length === 1) {
label = `${meta.label} · ${names[0]}`;
} else if (names.length > 1) {
label = `${meta.label} · ${names.length} 个板块`;
}
} else if (boardIds && boardIds.length > 0) {
label = `${meta.label} · ${boardIds.length} 个板块`;
}
}
return (
<span
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-bold leading-[1.6] ${
truncate ? "max-w-full whitespace-nowrap" : "whitespace-nowrap"
} ${className}`}
style={{ background: `var(${meta.softToken})`, color: `var(${meta.colorToken})` }}
title={title ?? label}
>
<Icon size={size} className="shrink-0" />
{truncate ? <span className="overflow-hidden text-ellipsis">{label}</span> : label}
</span>
);
}