feat: 实现完整的板块级RBAC内容审核系统
- 新增站长/超级管理员/管理员/板块管理员四级角色体系 - 实现实时权限快照加载与细粒度权限校验 - 新增内容审核队列与前后端页面 - 重构用户权限管理与站点管理逻辑 - 新增评论/帖子审核状态与通知推送 - 优化前端权限控制与角色徽章展示 - 修正数据库迁移与默认值问题
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
@@ -10,29 +11,114 @@ import {
|
||||
Palette,
|
||||
ShieldCheck,
|
||||
ArrowLeft,
|
||||
ClipboardCheck,
|
||||
} from "lucide-react";
|
||||
import type { User } from "@/lib/api";
|
||||
import { apiAdminPendingCounts } from "@/lib/api";
|
||||
import {
|
||||
canModerateAny,
|
||||
isAdminOrAbove,
|
||||
isSuperOrOwner,
|
||||
type RoleUserLike,
|
||||
} from "@/lib/roles";
|
||||
import Avatar from "@/components/Avatar";
|
||||
import RoleBadge from "@/components/RoleBadge";
|
||||
|
||||
interface NavItem {
|
||||
href: string;
|
||||
label: string;
|
||||
icon: LucideIcon;
|
||||
exact?: boolean;
|
||||
/** 按 /me 角色过滤可见性;最终权限以后端路由守卫为准 */
|
||||
visible: (u: RoleUserLike) => boolean;
|
||||
/** 是否携带待审核角标 */
|
||||
pendingBadge?: boolean;
|
||||
}
|
||||
|
||||
// 后台导航项:exact 为精确匹配(仪表盘 /admin),其余按路径前缀匹配
|
||||
const NAV_ITEMS: { href: string; label: string; icon: LucideIcon; exact?: boolean }[] = [
|
||||
{ href: "/admin", label: "仪表盘", icon: LayoutDashboard, exact: true },
|
||||
{ href: "/admin/users", label: "用户管理", icon: Users },
|
||||
{ href: "/admin/announcements", label: "公告管理", icon: Megaphone },
|
||||
{ href: "/admin/appearance", label: "外观设置", icon: Palette },
|
||||
const NAV_ITEMS: NavItem[] = [
|
||||
{ href: "/admin", label: "仪表盘", icon: LayoutDashboard, exact: true, visible: () => true },
|
||||
{
|
||||
href: "/admin/moderation",
|
||||
label: "内容审核",
|
||||
icon: ClipboardCheck,
|
||||
visible: (u) => canModerateAny(u),
|
||||
pendingBadge: true,
|
||||
},
|
||||
{
|
||||
href: "/admin/announcements",
|
||||
label: "公告管理",
|
||||
icon: Megaphone,
|
||||
visible: (u) => isAdminOrAbove(u.role),
|
||||
},
|
||||
{
|
||||
href: "/admin/users",
|
||||
label: "用户权限",
|
||||
icon: Users,
|
||||
visible: (u) => isSuperOrOwner(u.role),
|
||||
},
|
||||
{
|
||||
href: "/admin/appearance",
|
||||
label: "外观设置",
|
||||
icon: Palette,
|
||||
visible: (u) => isSuperOrOwner(u.role),
|
||||
},
|
||||
];
|
||||
|
||||
function isActive(pathname: string, href: string, exact?: boolean) {
|
||||
return exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
|
||||
}
|
||||
|
||||
/** 待审核数量轮询(30 秒);仅内容审核入口可见时启用 */
|
||||
function usePendingCounts(enabled: boolean) {
|
||||
const [counts, setCounts] = useState({ posts: 0, comments: 0 });
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let alive = true;
|
||||
const load = () => {
|
||||
apiAdminPendingCounts()
|
||||
.then((c) => {
|
||||
if (alive) setCounts(c);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
load();
|
||||
const t = setInterval(load, 30_000);
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === "visible") load();
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [enabled]);
|
||||
return counts.posts + counts.comments;
|
||||
}
|
||||
|
||||
function PendingBadge({ count }: { count: number }) {
|
||||
if (count <= 0) return null;
|
||||
return (
|
||||
<span
|
||||
className="ml-auto shrink-0 min-w-[20px] h-5 px-1.5 rounded-full inline-flex items-center justify-center text-[10.5px] font-extrabold tabular-nums"
|
||||
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
|
||||
aria-label={`${count} 条待审核`}
|
||||
>
|
||||
{count > 99 ? "99+" : count}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 桌面端后台侧边栏:品牌头 + 分组导航 + 返回站点 + 管理员身份卡。
|
||||
* 桌面端后台侧边栏:品牌头 + 分组导航 + 返回站点 + 身份卡。
|
||||
* 选中态复用全站导航语言(--nav-active-bg 淡底 + accent 文字),
|
||||
* 与 j13-bcard / 顶部 pill 保持一致。
|
||||
*/
|
||||
export function AdminSidebar({ user }: { user: User }) {
|
||||
const pathname = usePathname();
|
||||
const items = NAV_ITEMS.filter((i) => i.visible(user));
|
||||
const pendingTotal = usePendingCounts(items.some((i) => i.pendingBadge));
|
||||
|
||||
return (
|
||||
<div className="panel p-3">
|
||||
@@ -59,7 +145,7 @@ export function AdminSidebar({ user }: { user: User }) {
|
||||
<p className="field-label px-2 pb-1.5" style={{ marginBottom: 0 }}>
|
||||
站点管理
|
||||
</p>
|
||||
{NAV_ITEMS.map((item) => {
|
||||
{items.map((item) => {
|
||||
const active = isActive(pathname, item.href, item.exact);
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
@@ -76,6 +162,7 @@ export function AdminSidebar({ user }: { user: User }) {
|
||||
>
|
||||
<Icon size={16} className="shrink-0" style={{ color: active ? "var(--nav-active-ink)" : "var(--ink-3)" }} />
|
||||
{item.label}
|
||||
{item.pendingBadge && <PendingBadge count={pendingTotal} />}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
@@ -93,7 +180,7 @@ export function AdminSidebar({ user }: { user: User }) {
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* 管理员身份卡 */}
|
||||
{/* 身份卡:按当前角色显示对应徽章(站长为皇冠标识) */}
|
||||
<div className="flex items-center gap-2.5 mt-2 px-2.5 py-2.5 rounded-xl" style={{ background: "var(--panel-2)" }}>
|
||||
<Avatar name={user.nickname || user.username} src={user.avatar || undefined} size={32} />
|
||||
<div className="min-w-0 leading-tight">
|
||||
@@ -104,12 +191,8 @@ export function AdminSidebar({ user }: { user: User }) {
|
||||
@{user.username}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className="ml-auto shrink-0 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10.5px] font-bold leading-[1.6]"
|
||||
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
|
||||
>
|
||||
<ShieldCheck size={11} />
|
||||
管理员
|
||||
<span className="ml-auto shrink-0">
|
||||
<RoleBadge role={user.role} boardIds={user.board_ids} size={11} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -120,8 +203,10 @@ export function AdminSidebar({ user }: { user: User }) {
|
||||
* 移动端后台导航:横向滚动 pill,吸附在全站 Header 下方,
|
||||
* 窄屏下保持与桌面侧栏同等的切换能力且不占垂直空间。
|
||||
*/
|
||||
export function AdminNavMobile() {
|
||||
export function AdminNavMobile({ user }: { user: User }) {
|
||||
const pathname = usePathname();
|
||||
const items = NAV_ITEMS.filter((i) => i.visible(user));
|
||||
const pendingTotal = usePendingCounts(items.some((i) => i.pendingBadge));
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -135,7 +220,7 @@ export function AdminNavMobile() {
|
||||
}}
|
||||
>
|
||||
<nav className="flex items-center gap-2 overflow-x-auto" aria-label="后台导航">
|
||||
{NAV_ITEMS.map((item) => {
|
||||
{items.map((item) => {
|
||||
const active = isActive(pathname, item.href, item.exact);
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
@@ -152,6 +237,14 @@ export function AdminNavMobile() {
|
||||
>
|
||||
<Icon size={14} />
|
||||
{item.label}
|
||||
{item.pendingBadge && pendingTotal > 0 && (
|
||||
<span
|
||||
className="min-w-[18px] h-[18px] px-1 rounded-full inline-flex items-center justify-center text-[10px] font-extrabold tabular-nums"
|
||||
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
|
||||
>
|
||||
{pendingTotal > 99 ? "99+" : pendingTotal}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
|
||||
27
frontend/app/admin/Forbidden.tsx
Normal file
27
frontend/app/admin/Forbidden.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import Link from "next/link";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
|
||||
// 子页面细粒度权限守卫的统一无权限视图(写接口仍由后端 403 兜底)
|
||||
export default function Forbidden({
|
||||
text = "你没有访问该管理功能的权限,如有需要请联系站长调整角色。",
|
||||
}: {
|
||||
text?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="max-w-md mx-auto panel p-8 text-center">
|
||||
<span
|
||||
className="inline-flex w-14 h-14 rounded-full items-center justify-center mb-4"
|
||||
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
|
||||
>
|
||||
<ShieldAlert size={26} />
|
||||
</span>
|
||||
<h1 className="text-lg font-extrabold" style={{ color: "var(--ink)" }}>
|
||||
权限不足
|
||||
</h1>
|
||||
<p className="meta mt-2 text-[13px] leading-relaxed">{text}</p>
|
||||
<Link href="/admin" className="btn btn-primary mt-6">
|
||||
返回仪表盘
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import AnnouncementAdmin from "./AnnouncementAdmin";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "站点公告管理",
|
||||
};
|
||||
|
||||
// 管理员鉴权与 noindex 由 app/admin/layout.tsx 统一承担;本页只负责内容直出
|
||||
export default function AdminAnnouncementsPage() {
|
||||
// 公告管理仅管理员及以上可用(板块管理员无公告权;后端路由另有守卫)
|
||||
export default async function AdminAnnouncementsPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
return <Forbidden text="公告管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
return <AnnouncementAdmin />;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import type { Metadata } from "next";
|
||||
import { getPublicSettingsCached } from "@/lib/serverData";
|
||||
import { cookies } from "next/headers";
|
||||
import { getPublicSettingsCached, getMeCached } from "@/lib/serverData";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { isSuperOrOwner } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
import AppearanceAdmin from "./AppearanceAdmin";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "外观设置",
|
||||
};
|
||||
|
||||
// 管理员鉴权与 noindex 由 app/admin/layout.tsx 统一承担。
|
||||
// 主题色为公开设置:当前已保存值随 SSR 直出,避免面板初始闪动
|
||||
// 主题色为公开设置:当前已保存值随 SSR 直出,避免面板初始闪动;
|
||||
// 写操作仅超级管理员与站长可用(后端 PUT /settings 另有守卫)
|
||||
export default async function AdminAppearancePage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isSuperOrOwner(me.user.role)) {
|
||||
return <Forbidden text="外观设置仅超级管理员和站长可操作。" />;
|
||||
}
|
||||
const { accent } = await getPublicSettingsCached();
|
||||
return <AppearanceAdmin initialAccent={accent || ""} />;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { cookies } from "next/headers";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isStaff } from "@/lib/roles";
|
||||
import { AdminSidebar, AdminNavMobile } from "./AdminNav";
|
||||
|
||||
// 整个 /admin 树不进入索引(子页面无需重复声明)
|
||||
@@ -11,13 +12,13 @@ export const metadata: Metadata = {
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
// 权限以 Go 端 RequireAdmin 为唯一判定;这里仅决定管理界面是否直出,
|
||||
// 非管理员访问任意 /admin/* 时 SSR 统一给出无权限提示(所有写接口仍由后端 403 兜底)。
|
||||
// 权限以 Go 端 RequireStaff 为唯一判定;这里仅决定管理界面是否直出,
|
||||
// 非管理团队访问任意 /admin/* 时 SSR 统一给出无权限提示(所有写接口仍由后端 403 兜底)。
|
||||
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
|
||||
if (me.user?.role !== "admin") {
|
||||
if (!me.user || !isStaff(me.user.role)) {
|
||||
return (
|
||||
<div className="max-w-md mx-auto panel p-8 text-center mt-6 lg:mt-10">
|
||||
<span
|
||||
@@ -39,7 +40,7 @@ export default async function AdminLayout({ children }: { children: React.ReactN
|
||||
|
||||
return (
|
||||
<div>
|
||||
<AdminNavMobile />
|
||||
<AdminNavMobile user={me.user} />
|
||||
<div className="flex items-start gap-6 xl:gap-7">
|
||||
<aside className="hidden lg:block w-60 xl:w-64 shrink-0">
|
||||
<div className="sticky" style={{ top: 84 }}>
|
||||
|
||||
457
frontend/app/admin/moderation/ModerationAdmin.tsx
Normal file
457
frontend/app/admin/moderation/ModerationAdmin.tsx
Normal file
@@ -0,0 +1,457 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ClipboardCheck,
|
||||
FileText,
|
||||
Loader2,
|
||||
MessagesSquare,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
apiAdminPendingPosts,
|
||||
apiAdminPendingComments,
|
||||
apiAdminPendingCounts,
|
||||
apiAdminApprovePost,
|
||||
apiAdminRejectPost,
|
||||
apiAdminApproveComment,
|
||||
apiAdminRejectComment,
|
||||
type PendingCommentItem,
|
||||
type PendingCounts,
|
||||
type Post,
|
||||
} from "@/lib/api";
|
||||
import { formatRelative } from "@/lib/format";
|
||||
import { toast } from "@/lib/toast";
|
||||
import Avatar from "@/components/Avatar";
|
||||
|
||||
const PAGE_SIZE = 15;
|
||||
|
||||
type Tab = "posts" | "comments";
|
||||
|
||||
// 粗略去除 Markdown 标记,生成纯文本摘要
|
||||
function excerpt(md: string, max = 160): string {
|
||||
const text = md
|
||||
.replace(/```[\s\S]*?```/g, " ")
|
||||
.replace(/[#>*_`~\-]/g, "")
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
return text.length > max ? `${text.slice(0, max)}…` : text;
|
||||
}
|
||||
|
||||
export default function ModerationAdmin({
|
||||
initialPosts,
|
||||
initialPostsTotal,
|
||||
initError,
|
||||
}: {
|
||||
initialPosts: Post[];
|
||||
initialPostsTotal: number;
|
||||
initError: string;
|
||||
}) {
|
||||
const [tab, setTab] = useState<Tab>("posts");
|
||||
const [counts, setCounts] = useState<PendingCounts>({ posts: initialPostsTotal, comments: 0 });
|
||||
|
||||
// 帖子队列
|
||||
const [posts, setPosts] = useState<Post[]>(initialPosts);
|
||||
const [postsTotal, setPostsTotal] = useState(initialPostsTotal);
|
||||
const [postsPage, setPostsPage] = useState(1);
|
||||
|
||||
// 评论队列
|
||||
const [comments, setComments] = useState<PendingCommentItem[]>([]);
|
||||
const [commentsTotal, setCommentsTotal] = useState(0);
|
||||
const [commentsPage, setCommentsPage] = useState(1);
|
||||
const [commentsLoaded, setCommentsLoaded] = useState(false);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(initError);
|
||||
const [actingKey, setActingKey] = useState<string | null>(null);
|
||||
// 拒绝的二次内联确认(key: posts-<id> / comments-<id>,3 秒自动复原)
|
||||
const [confirmKey, setConfirmKey] = useState<string | null>(null);
|
||||
const confirmTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const refreshCounts = useCallback(() => {
|
||||
apiAdminPendingCounts()
|
||||
.then(setCounts)
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refreshCounts();
|
||||
}, [refreshCounts]);
|
||||
|
||||
const loadPosts = useCallback(async (page: number) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiAdminPendingPosts(page);
|
||||
setPosts(res.posts);
|
||||
setPostsTotal(res.total);
|
||||
setError("");
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "获取待审帖子失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadComments = useCallback(async (page: number) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await apiAdminPendingComments(page);
|
||||
setComments(res.comments);
|
||||
setCommentsTotal(res.total);
|
||||
setError("");
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "获取待审评论失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const switchTab = (t: Tab) => {
|
||||
if (t === tab) return;
|
||||
setTab(t);
|
||||
setError("");
|
||||
setConfirmKey(null);
|
||||
if (t === "comments" && !commentsLoaded) {
|
||||
setCommentsLoaded(true);
|
||||
loadComments(1);
|
||||
}
|
||||
};
|
||||
|
||||
const goPosts = (p: number) => {
|
||||
const next = Math.min(Math.max(1, p), Math.max(1, Math.ceil(postsTotal / PAGE_SIZE)));
|
||||
setPostsPage(next);
|
||||
loadPosts(next);
|
||||
};
|
||||
const goComments = (p: number) => {
|
||||
const next = Math.min(Math.max(1, p), Math.max(1, Math.ceil(commentsTotal / PAGE_SIZE)));
|
||||
setCommentsPage(next);
|
||||
loadComments(next);
|
||||
};
|
||||
|
||||
const armConfirm = (key: string) => {
|
||||
setConfirmKey(key);
|
||||
if (confirmTimer.current) clearTimeout(confirmTimer.current);
|
||||
confirmTimer.current = setTimeout(() => setConfirmKey(null), 3000);
|
||||
};
|
||||
|
||||
// 本地移除已处理项;当页清空且不在第一页时回退一页
|
||||
const afterAction = (kind: Tab, removedPage: number, removedPageItems: number, remaining: number) => {
|
||||
refreshCounts();
|
||||
setConfirmKey(null);
|
||||
if (remaining === 0 && removedPage > 1) {
|
||||
const prev = removedPage - 1;
|
||||
if (kind === "posts") {
|
||||
setPostsPage(prev);
|
||||
loadPosts(prev);
|
||||
} else {
|
||||
setCommentsPage(prev);
|
||||
loadComments(prev);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const act = async (
|
||||
key: string,
|
||||
kind: "posts" | "comments",
|
||||
id: number,
|
||||
approve: boolean,
|
||||
page: number,
|
||||
pageItems: number
|
||||
) => {
|
||||
// 首次点拒绝进入确认态,不执行
|
||||
if (!approve && confirmKey !== key) {
|
||||
armConfirm(key);
|
||||
return;
|
||||
}
|
||||
setActingKey(key);
|
||||
try {
|
||||
if (kind === "posts") {
|
||||
if (approve) await apiAdminApprovePost(id);
|
||||
else await apiAdminRejectPost(id);
|
||||
setPosts((list) => list.filter((p) => p.id !== id));
|
||||
setPostsTotal((t) => Math.max(0, t - 1));
|
||||
} else {
|
||||
if (approve) await apiAdminApproveComment(id);
|
||||
else await apiAdminRejectComment(id);
|
||||
setComments((list) => list.filter((c) => c.id !== id));
|
||||
setCommentsTotal((t) => Math.max(0, t - 1));
|
||||
}
|
||||
toast(approve ? "已通过审核,内容已公开" : "已拒绝,作者将收到通知", "ok");
|
||||
afterAction(kind, page, pageItems, pageItems - 1);
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : "操作失败");
|
||||
} finally {
|
||||
setActingKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
const totalPages = tab === "posts"
|
||||
? Math.max(1, Math.ceil(postsTotal / PAGE_SIZE))
|
||||
: Math.max(1, Math.ceil(commentsTotal / PAGE_SIZE));
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 页头 */}
|
||||
<div className="mb-5">
|
||||
<h1
|
||||
className="text-[22px] sm:text-[26px] font-extrabold tracking-tight flex items-center gap-2.5"
|
||||
style={{ color: "var(--ink)" }}
|
||||
>
|
||||
<span
|
||||
className="w-9 h-9 rounded-xl flex items-center justify-center"
|
||||
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
|
||||
>
|
||||
<ClipboardCheck size={18} />
|
||||
</span>
|
||||
内容审核
|
||||
</h1>
|
||||
<p className="meta mt-1.5 text-[12.5px]">
|
||||
普通用户发布的帖子与评论需审核通过后公开;板块管理员仅能处理授权板块的内容
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 队列切换 */}
|
||||
<div className="flex items-center gap-1.5 mb-4 flex-wrap" role="tablist" aria-label="审核队列">
|
||||
{(
|
||||
[
|
||||
{ key: "posts" as Tab, label: "待审帖子", count: counts.posts, icon: <FileText size={14} /> },
|
||||
{ key: "comments" as Tab, label: "待审评论", count: counts.comments, icon: <MessagesSquare size={14} /> },
|
||||
]
|
||||
).map((t) => {
|
||||
const active = tab === t.key;
|
||||
return (
|
||||
<button
|
||||
key={t.key}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={active}
|
||||
onClick={() => switchTab(t.key)}
|
||||
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-[13px] font-semibold transition-colors"
|
||||
style={
|
||||
active
|
||||
? { background: "var(--nav-active-bg)", color: "var(--nav-active-ink)" }
|
||||
: { color: "var(--ink-2)", background: "var(--panel-2)" }
|
||||
}
|
||||
>
|
||||
{t.icon}
|
||||
{t.label}
|
||||
<span
|
||||
className="text-[11px] tabular-nums rounded-full px-1.5 leading-[1.7]"
|
||||
style={{
|
||||
background: "var(--panel)",
|
||||
color: active ? "var(--nav-active-ink)" : "var(--ink-3)",
|
||||
}}
|
||||
>
|
||||
{t.count}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{error && <p className="alert-error mb-4">{error}</p>}
|
||||
|
||||
<div aria-busy={loading} style={{ opacity: loading ? 0.6 : 1, transition: "opacity .15s" }}>
|
||||
{tab === "posts" ? (
|
||||
posts.length === 0 ? (
|
||||
<EmptyQueue icon={<FileText size={22} />} text="暂无待审核帖子" />
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{posts.map((p) => {
|
||||
const key = `posts-${p.id}`;
|
||||
const busy = actingKey === key;
|
||||
const confirming = confirmKey === key;
|
||||
return (
|
||||
<div key={p.id} className="panel p-4 sm:p-5">
|
||||
<div className="flex items-center gap-2 flex-wrap mb-2.5">
|
||||
<Link
|
||||
href={`/board/${p.board.id}`}
|
||||
className="chip"
|
||||
style={{ fontSize: 11.5 }}
|
||||
>
|
||||
{p.board.name}
|
||||
</Link>
|
||||
<span className="meta text-[11.5px]">{formatRelative(p.created_at)}</span>
|
||||
</div>
|
||||
<Link
|
||||
href={`/post/${p.id}`}
|
||||
target="_blank"
|
||||
className="block text-[15.5px] font-extrabold tracking-tight leading-snug hover:text-[var(--accent)] transition-colors"
|
||||
style={{ color: "var(--ink)" }}
|
||||
>
|
||||
{p.title}
|
||||
</Link>
|
||||
<p
|
||||
className="mt-1.5 text-[13px] leading-relaxed line-clamp-3"
|
||||
style={{ color: "var(--ink-3)" }}
|
||||
>
|
||||
{excerpt(p.content) || "(无正文内容)"}
|
||||
</p>
|
||||
<div
|
||||
className="mt-3.5 flex items-center justify-between gap-3 flex-wrap pt-3"
|
||||
style={{ borderTop: "1px solid var(--line)" }}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Avatar name={p.user.nickname || p.user.username} src={p.user.avatar || undefined} size={26} />
|
||||
<span className="text-[12.5px] font-semibold truncate" style={{ color: "var(--ink-2)" }}>
|
||||
{p.user.nickname}
|
||||
</span>
|
||||
<span className="meta text-[11.5px] truncate">@{p.user.username}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => act(key, "posts", p.id, true, postsPage, posts.length)}
|
||||
className="btn btn-sm"
|
||||
style={{ background: "var(--ok-soft)", color: "var(--ok)" }}
|
||||
>
|
||||
{busy ? <Loader2 size={13} className="animate-spin" /> : <Check size={13} />}
|
||||
通过
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => act(key, "posts", p.id, false, postsPage, posts.length)}
|
||||
className="btn btn-sm"
|
||||
style={{
|
||||
background: confirming ? "var(--danger)" : "var(--danger-soft)",
|
||||
color: confirming ? "var(--accent-on)" : "var(--danger)",
|
||||
}}
|
||||
>
|
||||
{confirming ? "确认拒绝?" : <><X size={13} /> 拒绝</>}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
) : comments.length === 0 ? (
|
||||
<EmptyQueue icon={<MessagesSquare size={22} />} text="暂无待审核评论" />
|
||||
) : (
|
||||
<div className="panel overflow-hidden">
|
||||
{comments.map((c, idx) => {
|
||||
const key = `comments-${c.id}`;
|
||||
const busy = actingKey === key;
|
||||
const confirming = confirmKey === key;
|
||||
return (
|
||||
<div
|
||||
key={c.id}
|
||||
className="p-4 sm:p-5 flex items-start gap-3.5"
|
||||
style={idx === 0 ? undefined : { borderTop: "1px solid var(--line)" }}
|
||||
>
|
||||
<Avatar name={c.user.nickname || c.user.username} src={c.user.avatar || undefined} size={34} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-[13.5px] font-bold truncate" style={{ color: "var(--ink)" }}>
|
||||
{c.user.nickname}
|
||||
</span>
|
||||
<Link
|
||||
href={`/board/${c.board.id}`}
|
||||
className="chip"
|
||||
style={{ fontSize: 11 }}
|
||||
>
|
||||
{c.board.name}
|
||||
</Link>
|
||||
<span className="meta text-[11.5px]">{formatRelative(c.created_at)}</span>
|
||||
</div>
|
||||
<p
|
||||
className="mt-1.5 text-[13.5px] leading-relaxed rounded-xl px-3.5 py-2.5"
|
||||
style={{ background: "var(--panel-2)", color: "var(--ink-2)" }}
|
||||
>
|
||||
{c.content}
|
||||
</p>
|
||||
<Link
|
||||
href={`/post/${c.post_id}`}
|
||||
target="_blank"
|
||||
className="mt-1.5 block meta text-[12px] truncate hover:text-[var(--accent)] transition-colors"
|
||||
>
|
||||
所属帖子:《{c.post_title}》
|
||||
</Link>
|
||||
<div className="flex items-center gap-2 mt-3">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => act(key, "comments", c.id, true, commentsPage, comments.length)}
|
||||
className="btn btn-sm"
|
||||
style={{ background: "var(--ok-soft)", color: "var(--ok)" }}
|
||||
>
|
||||
{busy ? <Loader2 size={13} className="animate-spin" /> : <Check size={13} />}
|
||||
通过
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => act(key, "comments", c.id, false, commentsPage, comments.length)}
|
||||
className="btn btn-sm"
|
||||
style={{
|
||||
background: confirming ? "var(--danger)" : "var(--danger-soft)",
|
||||
color: confirming ? "var(--accent-on)" : "var(--danger)",
|
||||
}}
|
||||
>
|
||||
{confirming ? "确认拒绝?" : <><X size={13} /> 拒绝</>}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 分页 */}
|
||||
{totalPages > 1 && (
|
||||
<div
|
||||
className="mt-4 flex items-center justify-between gap-2 panel px-4 sm:px-5 py-3"
|
||||
>
|
||||
<span className="meta text-[12px] tabular-nums" style={{ color: "var(--ink-3)" }}>
|
||||
第 {tab === "posts" ? postsPage : commentsPage} / {totalPages} 页
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (tab === "posts" ? goPosts(postsPage - 1) : goComments(commentsPage - 1))}
|
||||
disabled={(tab === "posts" ? postsPage : commentsPage) <= 1 || loading}
|
||||
className="btn btn-line btn-sm"
|
||||
>
|
||||
<ChevronLeft size={14} /> 上一页
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (tab === "posts" ? goPosts(postsPage + 1) : goComments(commentsPage + 1))}
|
||||
disabled={(tab === "posts" ? postsPage : commentsPage) >= totalPages || loading}
|
||||
className="btn btn-line btn-sm"
|
||||
>
|
||||
下一页 <ChevronRight size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyQueue({ icon, text }: { icon: React.ReactNode; text: string }) {
|
||||
return (
|
||||
<div className="panel text-center py-16 px-6">
|
||||
<span
|
||||
className="inline-flex w-12 h-12 rounded-full items-center justify-center mb-3"
|
||||
style={{ background: "var(--panel-2)", color: "var(--ink-3)" }}
|
||||
>
|
||||
{icon}
|
||||
</span>
|
||||
<p className="font-bold text-[14.5px]" style={{ color: "var(--ink)" }}>
|
||||
{text}
|
||||
</p>
|
||||
<p className="meta mt-1.5 text-[12.5px]">新提交的内容会按时间顺序出现在这里</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
frontend/app/admin/moderation/page.tsx
Normal file
43
frontend/app/admin/moderation/page.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { fetchAdminPendingPosts, type Post } from "@/lib/api";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { canModerateAny } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
import ModerationAdmin from "./ModerationAdmin";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "内容审核",
|
||||
};
|
||||
|
||||
// 鉴权由 app/admin/layout.tsx 统一承担(RequireStaff + 板块隔离由后端兜底);
|
||||
// 帖子待审队列首屏 SSR 直出,评论队列由客户端进入时拉取
|
||||
export default async function ModerationPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
|
||||
// 板块管理员及以上且(对板块管理员)拥有授权板块
|
||||
if (!me.user || !canModerateAny(me.user)) {
|
||||
return <Forbidden text="你所在的角色没有内容审核权限,或尚未被授权任何板块。" />;
|
||||
}
|
||||
|
||||
let initialPosts: Post[] = [];
|
||||
let initialTotal = 0;
|
||||
let initError = "";
|
||||
try {
|
||||
const res = await fetchAdminPendingPosts(1, cookie || undefined);
|
||||
initialPosts = res.posts;
|
||||
initialTotal = res.total;
|
||||
} catch (e) {
|
||||
initError = e instanceof Error ? e.message : "获取待审核内容失败";
|
||||
}
|
||||
|
||||
return (
|
||||
<ModerationAdmin
|
||||
initialPosts={initialPosts}
|
||||
initialPostsTotal={initialTotal}
|
||||
initError={initError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -11,10 +11,12 @@ import {
|
||||
ChevronRight,
|
||||
UserPlus,
|
||||
LayoutGrid,
|
||||
ClipboardCheck,
|
||||
} from "lucide-react";
|
||||
import { fetchOverview, type OverviewResponse } from "@/lib/api";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { canModerateAny, isAdminOrAbove, isSuperOrOwner } from "@/lib/roles";
|
||||
import Avatar from "@/components/Avatar";
|
||||
import { formatRelative } from "@/lib/format";
|
||||
|
||||
@@ -204,33 +206,49 @@ export default async function AdminDashboardPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 快捷入口 */}
|
||||
{/* 快捷入口(按角色权限过滤,与侧边栏一致;后端路由另有守卫) */}
|
||||
<h2 className="sr-only">快捷管理</h2>
|
||||
<div className="grid sm:grid-cols-2 xl:grid-cols-3 gap-3 sm:gap-4 mt-4">
|
||||
<QuickLink
|
||||
href="/admin/users"
|
||||
icon={<Users size={18} />}
|
||||
title="用户管理"
|
||||
desc="查看全站成员,授予管理员权限或封禁违规账号"
|
||||
soft="var(--accent-soft)"
|
||||
color="var(--accent)"
|
||||
/>
|
||||
<QuickLink
|
||||
href="/admin/announcements"
|
||||
icon={<Megaphone size={18} />}
|
||||
title="公告管理"
|
||||
desc="发布、编辑与下线站点公告,支持标签颜色与草稿状态"
|
||||
soft="var(--clay-soft)"
|
||||
color="var(--clay)"
|
||||
/>
|
||||
<QuickLink
|
||||
href="/admin/appearance"
|
||||
icon={<Palette size={18} />}
|
||||
title="外观设置"
|
||||
desc="配置全站主题强调色,实时预览后保存并对所有用户生效"
|
||||
soft="var(--gold-soft)"
|
||||
color="var(--gold)"
|
||||
/>
|
||||
{canModerateAny(me.user) && (
|
||||
<QuickLink
|
||||
href="/admin/moderation"
|
||||
icon={<ClipboardCheck size={18} />}
|
||||
title="内容审核"
|
||||
desc="审核普通用户提交的帖子与评论,通过后内容公开可见"
|
||||
soft="var(--ok-soft)"
|
||||
color="var(--ok)"
|
||||
/>
|
||||
)}
|
||||
{isAdminOrAbove(me.user?.role) && (
|
||||
<QuickLink
|
||||
href="/admin/announcements"
|
||||
icon={<Megaphone size={18} />}
|
||||
title="公告管理"
|
||||
desc="发布、编辑与下线站点公告,支持标签颜色与草稿状态"
|
||||
soft="var(--clay-soft)"
|
||||
color="var(--clay)"
|
||||
/>
|
||||
)}
|
||||
{isSuperOrOwner(me.user?.role) && (
|
||||
<QuickLink
|
||||
href="/admin/users"
|
||||
icon={<Users size={18} />}
|
||||
title="用户权限"
|
||||
desc="查看全站成员,授予管理角色与板块授权,封禁违规账号"
|
||||
soft="var(--accent-soft)"
|
||||
color="var(--accent)"
|
||||
/>
|
||||
)}
|
||||
{isSuperOrOwner(me.user?.role) && (
|
||||
<QuickLink
|
||||
href="/admin/appearance"
|
||||
icon={<Palette size={18} />}
|
||||
title="外观设置"
|
||||
desc="配置全站主题强调色,实时预览后保存并对所有用户生效"
|
||||
soft="var(--gold-soft)"
|
||||
color="var(--gold)"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 成员与板块 */}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,8 @@ import { cookies } from "next/headers";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { fetchAdminUsers, type AdminUsersResponse } from "@/lib/api";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isSuperOrOwner } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
import UsersAdmin, { type UserFilter } from "./UsersAdmin";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -13,9 +15,9 @@ interface UsersPageProps {
|
||||
searchParams: Promise<{ q?: string; filter?: string; page?: string }>;
|
||||
}
|
||||
|
||||
// 筛选项映射为后端查询参数:管理员走 role,封禁走 status,其余不过滤
|
||||
// 筛选项映射为后端查询参数:管理团队走 role=staff,封禁走 status,其余不过滤
|
||||
function filterToQuery(filter: UserFilter): { role?: string; status?: string } {
|
||||
if (filter === "admin") return { role: "admin" };
|
||||
if (filter === "staff") return { role: "staff" };
|
||||
if (filter === "banned") return { status: "banned" };
|
||||
return {};
|
||||
}
|
||||
@@ -24,12 +26,17 @@ function filterToQuery(filter: UserFilter): { role?: string; status?: string } {
|
||||
export default async function AdminUsersPage({ searchParams }: UsersPageProps) {
|
||||
const sp = await searchParams;
|
||||
const q = sp.q?.trim() || "";
|
||||
const filter: UserFilter = sp.filter === "admin" || sp.filter === "banned" ? sp.filter : "all";
|
||||
const filter: UserFilter = sp.filter === "staff" || sp.filter === "banned" ? sp.filter : "all";
|
||||
const page = Math.max(1, parseInt(sp.page || "1", 10) || 1);
|
||||
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
|
||||
// 仅超级管理员与站长可管理用户与角色
|
||||
if (!me.user || !isSuperOrOwner(me.user.role)) {
|
||||
return <Forbidden text="用户与角色权限仅超级管理员和站长可操作。" />;
|
||||
}
|
||||
|
||||
let initial: AdminUsersResponse | null = null;
|
||||
let initError = "";
|
||||
try {
|
||||
@@ -44,6 +51,7 @@ export default async function AdminUsersPage({ searchParams }: UsersPageProps) {
|
||||
initError={initError}
|
||||
initialQuery={{ q, filter, page }}
|
||||
currentUserId={me.user?.id ?? 0}
|
||||
currentUserRole={me.user?.role ?? ""}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { ChevronRight, PenSquare } from "lucide-react";
|
||||
import { apiCreatePost, apiMe, fetchBoards, type Board } from "@/lib/api";
|
||||
import { toast } from "@/lib/toast";
|
||||
|
||||
export default function ComposePage() {
|
||||
const router = useRouter();
|
||||
@@ -44,6 +45,10 @@ export default function ComposePage() {
|
||||
post_type: "normal",
|
||||
});
|
||||
if (res.post) {
|
||||
// 普通用户发帖进入待审核队列:跳转详情页(作者可见)并提示
|
||||
if (res.post.status === "pending") {
|
||||
toast("已提交,等待审核通过后公开", "ok");
|
||||
}
|
||||
router.push(`/post/${res.post.id}`);
|
||||
} else {
|
||||
setError(res.error || "发帖失败");
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Heart, MessageCircle, CheckCheck, Bell } from "lucide-react";
|
||||
import { Heart, MessageCircle, CheckCheck, Bell, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { apiMarkRead, apiMarkAllRead, type NotificationsResponse, type NotificationItem } from "@/lib/api";
|
||||
|
||||
/**
|
||||
@@ -65,7 +65,30 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
||||
</div>
|
||||
) : (
|
||||
<div className="panel overflow-hidden p-0">
|
||||
{notifications.map((n, i) => (
|
||||
{notifications.map((n, i) => {
|
||||
const approval = n.type === "approved" || n.type === "rejected";
|
||||
const iconNode = n.type === "approved"
|
||||
? <CheckCircle2 size={16} />
|
||||
: n.type === "rejected"
|
||||
? <XCircle size={16} />
|
||||
: n.type === "like"
|
||||
? <Heart size={16} />
|
||||
: <MessageCircle size={16} />;
|
||||
const iconColor = n.type === "approved"
|
||||
? "var(--ok)"
|
||||
: n.type === "rejected"
|
||||
? "var(--danger)"
|
||||
: n.type === "like"
|
||||
? "var(--clay)"
|
||||
: "var(--accent)";
|
||||
const iconBg = n.type === "approved"
|
||||
? "var(--ok-soft)"
|
||||
: n.type === "rejected"
|
||||
? "var(--danger-soft)"
|
||||
: n.type === "like"
|
||||
? "var(--clay-soft)"
|
||||
: "var(--accent-soft)";
|
||||
return (
|
||||
<button
|
||||
key={n.id}
|
||||
onClick={() => handleClick(n)}
|
||||
@@ -78,30 +101,37 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
||||
>
|
||||
<span
|
||||
className="w-10 h-10 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: iconColor, background: iconBg }}
|
||||
>
|
||||
{n.type === "like" ? <Heart size={16} /> : <MessageCircle size={16} />}
|
||||
{iconNode}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm leading-snug" style={{ color: "var(--ink)" }}>
|
||||
<Link
|
||||
href={`/u/${n.actor.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="font-semibold hover:text-[var(--accent)] transition-colors"
|
||||
>
|
||||
{n.actor.nickname}
|
||||
</Link>{" "}
|
||||
<span className="meta">
|
||||
{n.type === "comment"
|
||||
? "评论了你的帖子"
|
||||
: n.type === "reply"
|
||||
? "回复了你的评论"
|
||||
: "点赞了你的帖子"}
|
||||
</span>
|
||||
{approval ? (
|
||||
<span
|
||||
className="font-bold"
|
||||
style={{ color: n.type === "approved" ? "var(--ok)" : "var(--danger)" }}
|
||||
>
|
||||
{n.type === "approved" ? "审核通过" : "未通过审核"}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<Link
|
||||
href={`/u/${n.actor.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="font-semibold hover:text-[var(--accent)] transition-colors"
|
||||
>
|
||||
{n.actor.nickname}
|
||||
</Link>{" "}
|
||||
<span className="meta">
|
||||
{n.type === "comment"
|
||||
? "评论了你的帖子"
|
||||
: n.type === "reply"
|
||||
? "回复了你的评论"
|
||||
: "点赞了你的帖子"}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-sm mt-1 truncate" style={{ color: "var(--ink-2)" }}>
|
||||
《{n.post.title}》
|
||||
@@ -117,7 +147,8 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
||||
<span className="w-2.5 h-2.5 shrink-0 mt-2 rounded-full" style={{ background: "var(--clay)" }} />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import { fetchPostDetail, apiMe, apiUpdatePost, type Post, type User } from "@/lib/api";
|
||||
import { canModerateBoard } from "@/lib/roles";
|
||||
|
||||
interface EditPageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
@@ -36,7 +37,10 @@ export default function EditPostPage({ params }: EditPageProps) {
|
||||
setTags(postData.post.tags || "");
|
||||
const u = meData.user;
|
||||
setUser(u || null);
|
||||
if (!u || (u.id !== postData.post.user.id && u.role !== "admin")) {
|
||||
if (
|
||||
!u ||
|
||||
(u.id !== postData.post.user.id && !canModerateBoard(u, postData.post.board_id))
|
||||
) {
|
||||
router.push(`/post/${id}`);
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { cookies } from "next/headers";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import {
|
||||
@@ -31,6 +32,8 @@ import ReadingProgress from "@/components/ReadingProgress";
|
||||
import PostToc, { type TocItem } from "@/components/PostToc";
|
||||
import MobilePostBar from "@/components/MobilePostBar";
|
||||
import Avatar from "@/components/Avatar";
|
||||
import RoleBadge from "@/components/RoleBadge";
|
||||
import { isStaff } from "@/lib/roles";
|
||||
import { IconComment, IconEye } from "@/components/Icons";
|
||||
|
||||
interface PageProps {
|
||||
@@ -42,7 +45,8 @@ interface PageProps {
|
||||
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const { post } = await fetchPostDetail(id);
|
||||
// 带登录态:作者/管理团队看待审帖时标签标题也应是真实标题而非"帖子不存在"
|
||||
const { post } = await fetchPostDetail(id, authCookieHeader(await cookies()));
|
||||
return {
|
||||
title: post.title,
|
||||
description: post.content.slice(0, 160),
|
||||
@@ -157,14 +161,7 @@ function AuthorRailCard({ profile }: { profile: UserProfile }) {
|
||||
>
|
||||
{u.nickname}
|
||||
</Link>
|
||||
{u.role === "admin" && (
|
||||
<span
|
||||
className="chip mt-1.5"
|
||||
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
|
||||
>
|
||||
管理员
|
||||
</span>
|
||||
)}
|
||||
{u.role !== "user" && <RoleBadge role={u.role} boardIds={u.board_ids} />}
|
||||
</div>
|
||||
</div>
|
||||
<p className="meta mt-3">{formatYearMonth(u.created_at)} 加入</p>
|
||||
@@ -295,13 +292,8 @@ function AuthorCardStacked({ profile }: { profile: UserProfile }) {
|
||||
>
|
||||
{profile.user.nickname}
|
||||
</Link>
|
||||
{profile.user.role === "admin" && (
|
||||
<span
|
||||
className="chip"
|
||||
style={{ background: "var(--accent-soft)", color: "var(--accent)", borderColor: "transparent" }}
|
||||
>
|
||||
管理员
|
||||
</span>
|
||||
{profile.user.role !== "user" && (
|
||||
<RoleBadge role={profile.user.role} boardIds={profile.user.board_ids} />
|
||||
)}
|
||||
</div>
|
||||
<p className="meta mt-1">
|
||||
@@ -322,11 +314,17 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
const sp = await searchParams;
|
||||
const commentPage = Math.max(1, parseInt(sp.page || "1", 10) || 1);
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const { post } = await fetchPostDetail(id, cookie);
|
||||
// 待审/被拒帖子对无权访问者由后端返回 404,这里落到全局 not-found 页而非 500
|
||||
let post: Awaited<ReturnType<typeof fetchPostDetail>>["post"];
|
||||
try {
|
||||
({ post } = await fetchPostDetail(id, cookie));
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// 评论 / 当前用户 / 作者资料 / 同板块热议并行拉取;侧栏数据失败一律静默降级,不阻塞正文
|
||||
const [commentsData, me, profile, relatedData] = await Promise.all([
|
||||
fetchComments(id, commentPage),
|
||||
fetchComments(id, commentPage, cookie),
|
||||
getMeCached(cookie || undefined),
|
||||
fetchUserProfile(String(post.user.id), 1, cookie).catch(() => null),
|
||||
fetchPosts(1, 8, post.board_id, "hot", "", false, cookie).catch(() => null),
|
||||
@@ -340,6 +338,10 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
const edited =
|
||||
new Date(post.updated_at).getTime() - new Date(post.created_at).getTime() > 60_000;
|
||||
|
||||
// 非公开帖(待审/未通过)仅作者本人与管理团队可看,顶部给出醒目状态
|
||||
const isPublished = post.status === "published";
|
||||
const canSeeStatus = !!me.user && (me.user.id === post.user.id || isStaff(me.user.role));
|
||||
|
||||
const jsonLd = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "DiscussionForumPosting",
|
||||
@@ -409,6 +411,22 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
<div className="flex items-center gap-2 mb-4 flex-wrap">
|
||||
{post.pinned > 0 && <span className="badge-pin">置顶</span>}
|
||||
{post.recommended && <span className="badge-rec">推荐</span>}
|
||||
{!isPublished && canSeeStatus && post.status === "pending" && (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[11.5px] font-bold"
|
||||
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
|
||||
>
|
||||
等待审核
|
||||
</span>
|
||||
)}
|
||||
{!isPublished && canSeeStatus && post.status === "rejected" && (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[11.5px] font-bold"
|
||||
style={{ background: "var(--danger-soft)", color: "var(--danger)" }}
|
||||
>
|
||||
未通过审核
|
||||
</span>
|
||||
)}
|
||||
<Link href={`/board/${post.board.id}`} className="chip">
|
||||
{post.board.name}
|
||||
</Link>
|
||||
@@ -435,7 +453,7 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
</Link>
|
||||
</div>
|
||||
{/* 管理操作已收进单个下拉按钮;普通读者此处不渲染内容 */}
|
||||
<PostActions postId={id} authorId={post.user.id} pinned={post.pinned} recommended={post.recommended} />
|
||||
<PostActions postId={id} authorId={post.user.id} boardId={post.board_id} pinned={post.pinned} recommended={post.recommended} />
|
||||
</div>
|
||||
|
||||
{/* 元信息条:阅读数据居左、发布/更新时间居右(窄屏自动折行);
|
||||
@@ -496,15 +514,32 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CommentSection
|
||||
postId={id}
|
||||
comments={comments}
|
||||
total={commentsData.total}
|
||||
totalComments={commentsData.total_comments}
|
||||
page={commentsData.page}
|
||||
size={commentsData.size}
|
||||
user={me.user}
|
||||
/>
|
||||
{/* 非公开帖不开放评论(后端同样拒绝),给出状态提示 */}
|
||||
{isPublished ? (
|
||||
<CommentSection
|
||||
postId={id}
|
||||
boardId={post.board_id}
|
||||
comments={comments}
|
||||
total={commentsData.total}
|
||||
totalComments={commentsData.total_comments}
|
||||
page={commentsData.page}
|
||||
size={commentsData.size}
|
||||
user={me.user}
|
||||
/>
|
||||
) : (
|
||||
<section className="panel p-6 sm:p-8 mt-6 text-center" aria-label="评论区">
|
||||
<p className="text-[14px] font-bold" style={{ color: "var(--ink-2)" }}>
|
||||
{post.status === "pending" ? "帖子审核通过后开放评论" : "帖子未通过审核,评论已关闭"}
|
||||
</p>
|
||||
<p className="meta mt-1.5 text-[12.5px]">
|
||||
{me.user?.id === post.user.id
|
||||
? post.status === "pending"
|
||||
? "你的帖子正在等待管理员审核,请留意通知"
|
||||
: "如有疑问可联系管理团队"
|
||||
: "审核通过后评论区将自动开放"}
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* 窄屏相关讨论(lg 起由右栏承载) */}
|
||||
<div className="lg:hidden mt-6">
|
||||
|
||||
@@ -12,6 +12,8 @@ import UserProfileContent from "./UserProfileContent";
|
||||
import ProfileForm from "./ProfileForm";
|
||||
import PasswordForm from "./PasswordForm";
|
||||
import Avatar from "@/components/Avatar";
|
||||
import RoleBadge from "@/components/RoleBadge";
|
||||
import { roleMeta } from "@/lib/roles";
|
||||
|
||||
interface UserPageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
@@ -84,7 +86,6 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
||||
}
|
||||
|
||||
const u = data.user;
|
||||
const isAdmin = u.role === "admin";
|
||||
const joinDate = new Date(u.created_at).toLocaleDateString("zh-CN");
|
||||
const showPoints = data.stats.points > 0;
|
||||
|
||||
@@ -176,13 +177,8 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
||||
>
|
||||
{u.nickname || u.username}
|
||||
</h1>
|
||||
{isAdmin && (
|
||||
<span
|
||||
className="text-[11px] font-bold px-2 py-0.5 rounded-full"
|
||||
style={{ background: "var(--gold-soft)", color: "var(--gold)" }}
|
||||
>
|
||||
管理员
|
||||
</span>
|
||||
{u.role !== "user" && (
|
||||
<RoleBadge role={u.role} boardIds={u.board_ids} />
|
||||
)}
|
||||
</div>
|
||||
<p className="meta mt-1 flex items-center gap-1.5 text-[12.5px] flex-wrap">
|
||||
@@ -342,7 +338,7 @@ export default async function UserPage({ params, searchParams }: UserPageProps)
|
||||
<Shield size={11.5} /> 角色
|
||||
</p>
|
||||
<p className="text-[13px] font-semibold mt-0.5" style={{ color: "var(--ink)" }}>
|
||||
{isAdmin ? "管理员" : "普通用户"}
|
||||
{roleMeta(u.role).label}
|
||||
</p>
|
||||
</div>
|
||||
<div className="pt-3 border-t" style={{ borderColor: "var(--line)" }}>
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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)" }} /> 管理面板
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
70
frontend/components/RoleBadge.tsx
Normal file
70
frontend/components/RoleBadge.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -27,6 +27,8 @@ export interface User {
|
||||
nickname: string;
|
||||
avatar: string;
|
||||
role: string;
|
||||
// 板块管理员被授权的板块(仅 /api/me 返回;前端据此渲染审核入口/按钮)
|
||||
board_ids?: number[];
|
||||
// 仅 /api/me 与 /api/profile 响应中返回(用户自身敏感信息)
|
||||
email?: string;
|
||||
signature?: string;
|
||||
@@ -215,6 +217,7 @@ export interface UserProfile {
|
||||
avatar: string;
|
||||
signature: string;
|
||||
role: string;
|
||||
board_ids?: number[];
|
||||
created_at: string;
|
||||
};
|
||||
stats: {
|
||||
@@ -248,7 +251,7 @@ export interface NotificationItem {
|
||||
id: number;
|
||||
user_id: number;
|
||||
actor_id: number;
|
||||
type: "comment" | "reply" | "like";
|
||||
type: "comment" | "reply" | "like" | "approved" | "rejected";
|
||||
post_id: number;
|
||||
comment_id: number;
|
||||
content: string;
|
||||
@@ -411,9 +414,16 @@ export async function fetchPostDetail(id: string, cookieHeader?: string): Promis
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchComments(postId: string, page = 1): Promise<CommentsResponse> {
|
||||
export async function fetchComments(
|
||||
postId: string,
|
||||
page = 1,
|
||||
cookieHeader?: string
|
||||
): Promise<CommentsResponse> {
|
||||
const params = new URLSearchParams({ page: String(page), size: "20" });
|
||||
const res = await fetch(`${API_BASE}/api/posts/${postId}/comments?${params}`, ssrInit());
|
||||
const res = await fetch(
|
||||
`${API_BASE}/api/posts/${postId}/comments?${params}`,
|
||||
ssrInit(cookieHeaders(cookieHeader))
|
||||
);
|
||||
if (!res.ok) throw new Error("获取评论失败");
|
||||
return res.json();
|
||||
}
|
||||
@@ -784,7 +794,7 @@ export async function apiAdminDeleteAnnouncement(id: number): Promise<void> {
|
||||
|
||||
// ===== 用户管理(管理员) =====
|
||||
|
||||
// 后台用户列表项:email/最近活跃仅管理员接口返回
|
||||
// 后台用户列表项:email/最近活跃/登录 IP 仅管理员接口返回
|
||||
export interface AdminUser {
|
||||
id: number;
|
||||
username: string;
|
||||
@@ -792,12 +802,33 @@ export interface AdminUser {
|
||||
email: string;
|
||||
avatar: string;
|
||||
signature: string;
|
||||
role: "user" | "admin" | string;
|
||||
role: string; // user | board_admin | admin | super_admin | owner
|
||||
board_ids: number[]; // 板块管理员的授权板块
|
||||
banned: boolean;
|
||||
post_count: number;
|
||||
comment_count: number;
|
||||
created_at: string;
|
||||
last_seen_at: string | null;
|
||||
online: boolean; // last_seen_at 在 5 分钟内
|
||||
last_login_ip: string;
|
||||
last_login_at: string | null;
|
||||
}
|
||||
|
||||
// 登录历史记录
|
||||
export interface LoginLog {
|
||||
id: number;
|
||||
user_id: number;
|
||||
username: string;
|
||||
ip: string;
|
||||
user_agent: string;
|
||||
success: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface LoginLogsResponse {
|
||||
logs: LoginLog[];
|
||||
total: number;
|
||||
page: number;
|
||||
}
|
||||
|
||||
export interface AdminUserSummary {
|
||||
@@ -846,6 +877,19 @@ export async function fetchAdminUsers(
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// SSR 待审核帖子首页(转发管理团队 cookie 直连后端);权限不足时抛错由页面层处理
|
||||
export async function fetchAdminPendingPosts(
|
||||
page = 1,
|
||||
cookieHeader?: string
|
||||
): Promise<{ posts: Post[]; total: number; page: number }> {
|
||||
const res = await fetch(
|
||||
`${API_BASE}/api/admin/moderation/pending-posts?page=${page}`,
|
||||
ssrInit(cookieHeaders(cookieHeader))
|
||||
);
|
||||
if (!res.ok) throw new Error("获取待审核帖子失败");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// 客户端后台用户列表(走 rewrite,携带 cookie + CSRF)
|
||||
export async function apiAdminListUsers(query: AdminUsersQuery = {}): Promise<AdminUsersResponse> {
|
||||
const res = await fetchWithRefresh(`/api/admin/users?${adminUsersParams(query)}`, {
|
||||
@@ -856,21 +900,37 @@ export async function apiAdminListUsers(query: AdminUsersQuery = {}): Promise<Ad
|
||||
return data as AdminUsersResponse;
|
||||
}
|
||||
|
||||
// 变更用户角色:role 仅接受 "user" | "admin"
|
||||
// 变更用户管理角色与板块授权:
|
||||
// role 接受 user/board_admin/admin/super_admin(owner 不可授予);
|
||||
// board_admin 必须携带至少一个 board_ids
|
||||
export async function apiAdminSetUserRole(
|
||||
id: number,
|
||||
role: "user" | "admin"
|
||||
role: string,
|
||||
boardIds?: number[]
|
||||
): Promise<{ user: AdminUser }> {
|
||||
const res = await fetchWithRefresh(`/api/admin/users/${id}/role`, {
|
||||
method: "PUT",
|
||||
headers: clientHeaders({ "Content-Type": "application/json" }),
|
||||
body: JSON.stringify({ role }),
|
||||
body: JSON.stringify({ role, board_ids: boardIds ?? [] }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || "角色更新失败");
|
||||
return data as { user: AdminUser };
|
||||
}
|
||||
|
||||
// 某用户的登录历史(IP/UA/成败)
|
||||
export async function apiAdminUserLoginLogs(
|
||||
id: number,
|
||||
page = 1
|
||||
): Promise<LoginLogsResponse> {
|
||||
const res = await fetchWithRefresh(`/api/admin/users/${id}/login-logs?page=${page}`, {
|
||||
headers: clientHeaders(),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || "获取登录历史失败");
|
||||
return data as LoginLogsResponse;
|
||||
}
|
||||
|
||||
// 封禁 / 解封用户
|
||||
export async function apiAdminSetUserBan(
|
||||
id: number,
|
||||
@@ -905,3 +965,80 @@ export async function apiUpdateSiteSettings(accent: string): Promise<PublicSetti
|
||||
if (!res.ok) throw new Error(data.error || "保存设置失败");
|
||||
return { accent: data.accent ?? "" };
|
||||
}
|
||||
|
||||
// ===== 板块(客户端,供角色授权弹窗勾选) =====
|
||||
|
||||
export async function apiListBoards(): Promise<{ boards: Board[] }> {
|
||||
const res = await fetchWithRefresh("/api/boards", { headers: clientHeaders() });
|
||||
if (!res.ok) throw new Error("获取板块失败");
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// ===== 内容审核队列 =====
|
||||
|
||||
export interface PendingCommentItem {
|
||||
id: number;
|
||||
post_id: number;
|
||||
post_title: string;
|
||||
board_id: number;
|
||||
board: Board;
|
||||
content: string;
|
||||
created_at: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface PendingCounts {
|
||||
posts: number;
|
||||
comments: number;
|
||||
}
|
||||
|
||||
export async function apiAdminPendingPosts(page = 1): Promise<{
|
||||
posts: Post[];
|
||||
total: number;
|
||||
page: number;
|
||||
}> {
|
||||
const res = await fetchWithRefresh(`/api/admin/moderation/pending-posts?page=${page}`, {
|
||||
headers: clientHeaders(),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || "获取待审帖子失败");
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function apiAdminPendingComments(page = 1): Promise<{
|
||||
comments: PendingCommentItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
}> {
|
||||
const res = await fetchWithRefresh(`/api/admin/moderation/pending-comments?page=${page}`, {
|
||||
headers: clientHeaders(),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || "获取待审评论失败");
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function apiAdminPendingCounts(): Promise<PendingCounts> {
|
||||
const res = await fetchWithRefresh("/api/admin/moderation/counts", {
|
||||
headers: clientHeaders(),
|
||||
});
|
||||
if (!res.ok) return { posts: 0, comments: 0 };
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async function moderationAction(url: string): Promise<void> {
|
||||
const res = await fetchWithRefresh(url, { method: "PUT", headers: clientHeaders() });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.error || "操作失败");
|
||||
}
|
||||
}
|
||||
|
||||
export const apiAdminApprovePost = (id: number) =>
|
||||
moderationAction(`/api/admin/moderation/posts/${id}/approve`);
|
||||
export const apiAdminRejectPost = (id: number) =>
|
||||
moderationAction(`/api/admin/moderation/posts/${id}/reject`);
|
||||
export const apiAdminApproveComment = (id: number) =>
|
||||
moderationAction(`/api/admin/moderation/comments/${id}/approve`);
|
||||
export const apiAdminRejectComment = (id: number) =>
|
||||
moderationAction(`/api/admin/moderation/comments/${id}/reject`);
|
||||
|
||||
127
frontend/lib/roles.ts
Normal file
127
frontend/lib/roles.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
// 角色与权限中枢:与后端 model.Role / service.Actor 保持单一对应关系。
|
||||
// 前端只做"是否展示入口/按钮"的判定,所有最终权限以后端校验为准。
|
||||
|
||||
export const ROLES = {
|
||||
USER: "user",
|
||||
BOARD_ADMIN: "board_admin",
|
||||
ADMIN: "admin",
|
||||
SUPER_ADMIN: "super_admin",
|
||||
OWNER: "owner",
|
||||
} as const;
|
||||
|
||||
export type RoleKey = (typeof ROLES)[keyof typeof ROLES];
|
||||
|
||||
// 角色等级(与后端 model.RoleLevel 一致),未知角色按普通用户处理
|
||||
export const ROLE_LEVEL: Record<string, number> = {
|
||||
[ROLES.USER]: 0,
|
||||
[ROLES.BOARD_ADMIN]: 30,
|
||||
[ROLES.ADMIN]: 50,
|
||||
[ROLES.SUPER_ADMIN]: 80,
|
||||
[ROLES.OWNER]: 100,
|
||||
};
|
||||
|
||||
export function roleLevel(role?: string | null): number {
|
||||
return ROLE_LEVEL[role ?? ""] ?? 0;
|
||||
}
|
||||
|
||||
/** 管理团队成员(板块管理员及以上) */
|
||||
export function isStaff(role?: string | null): boolean {
|
||||
return roleLevel(role) >= ROLE_LEVEL[ROLES.BOARD_ADMIN];
|
||||
}
|
||||
|
||||
/** 管理员及以上(全站内容管理:置顶/加精/公告) */
|
||||
export function isAdminOrAbove(role?: string | null): boolean {
|
||||
return roleLevel(role) >= ROLE_LEVEL[ROLES.ADMIN];
|
||||
}
|
||||
|
||||
/** 超级管理员及以上(用户与权限、站点设置) */
|
||||
export function isSuperOrOwner(role?: string | null): boolean {
|
||||
return roleLevel(role) >= ROLE_LEVEL[ROLES.SUPER_ADMIN];
|
||||
}
|
||||
|
||||
/** 站长(唯一,不可被操作) */
|
||||
export function isOwner(role?: string | null): boolean {
|
||||
return role === ROLES.OWNER;
|
||||
}
|
||||
|
||||
/** 携带板块授权的最小用户形状(/me、帖子详情作者等均满足) */
|
||||
export interface RoleUserLike {
|
||||
role?: string | null;
|
||||
board_ids?: number[] | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 能否管理指定板块的内容(帖子/评论的编辑删除审核):
|
||||
* 管理员及以上不限板块;板块管理员仅限被授权板块
|
||||
*/
|
||||
export function canModerateBoard(
|
||||
user: RoleUserLike | null | undefined,
|
||||
boardId: number | null | undefined
|
||||
): boolean {
|
||||
if (!user) return false;
|
||||
if (isAdminOrAbove(user.role)) return true;
|
||||
if (user.role !== ROLES.BOARD_ADMIN || !boardId) return false;
|
||||
return (user.board_ids ?? []).includes(boardId);
|
||||
}
|
||||
|
||||
/** 是否拥有任意板块的内容审核权(后台"内容审核"入口) */
|
||||
export function canModerateAny(user: RoleUserLike | null | undefined): boolean {
|
||||
if (!user) return false;
|
||||
if (isAdminOrAbove(user.role)) return true;
|
||||
return user.role === ROLES.BOARD_ADMIN && (user.board_ids?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** 角色图标 key(RoleBadge 负责映射到具体图标,集中配置便于替换) */
|
||||
export type RoleIconKey = "crown" | "shield-star" | "shield" | "shield-board" | "user";
|
||||
|
||||
export interface RoleMeta {
|
||||
key: RoleKey;
|
||||
label: string;
|
||||
icon: RoleIconKey;
|
||||
/** 主色使用的 CSS token 名(RoleBadge 取 var(--token)) */
|
||||
colorToken: string;
|
||||
softToken: string;
|
||||
}
|
||||
|
||||
// 各管理角色的图标与配色集中配置;站长固定使用皇冠站长标识
|
||||
export const ROLE_META: Record<RoleKey, RoleMeta> = {
|
||||
[ROLES.OWNER]: {
|
||||
key: ROLES.OWNER,
|
||||
label: "站长",
|
||||
icon: "crown",
|
||||
colorToken: "--gold",
|
||||
softToken: "--gold-soft",
|
||||
},
|
||||
[ROLES.SUPER_ADMIN]: {
|
||||
key: ROLES.SUPER_ADMIN,
|
||||
label: "超级管理员",
|
||||
icon: "shield-star",
|
||||
colorToken: "--accent",
|
||||
softToken: "--accent-soft",
|
||||
},
|
||||
[ROLES.ADMIN]: {
|
||||
key: ROLES.ADMIN,
|
||||
label: "管理员",
|
||||
icon: "shield",
|
||||
colorToken: "--accent",
|
||||
softToken: "--accent-soft",
|
||||
},
|
||||
[ROLES.BOARD_ADMIN]: {
|
||||
key: ROLES.BOARD_ADMIN,
|
||||
label: "板块管理员",
|
||||
icon: "shield-board",
|
||||
colorToken: "--accent",
|
||||
softToken: "--accent-soft",
|
||||
},
|
||||
[ROLES.USER]: {
|
||||
key: ROLES.USER,
|
||||
label: "普通用户",
|
||||
icon: "user",
|
||||
colorToken: "--ink-3",
|
||||
softToken: "--panel-2",
|
||||
},
|
||||
};
|
||||
|
||||
export function roleMeta(role?: string | null): RoleMeta {
|
||||
return ROLE_META[(role as RoleKey)] ?? ROLE_META.user;
|
||||
}
|
||||
4
frontend/next-env.d.ts
vendored
4
frontend/next-env.d.ts
vendored
@@ -1,7 +1,7 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/dev/types/routes.d.ts";
|
||||
import "./.next/dev/types/root-params.d.ts";
|
||||
import "./.next/types/routes.d.ts";
|
||||
import "./.next/types/root-params.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
|
||||
Reference in New Issue
Block a user