feat: 实现完整的板块级RBAC内容审核系统
- 新增站长/超级管理员/管理员/板块管理员四级角色体系 - 实现实时权限快照加载与细粒度权限校验 - 新增内容审核队列与前后端页面 - 重构用户权限管理与站点管理逻辑 - 新增评论/帖子审核状态与通知推送 - 优化前端权限控制与角色徽章展示 - 修正数据库迁移与默认值问题
This commit is contained in:
22
backend/handler/actor.go
Normal file
22
backend/handler/actor.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
)
|
||||
|
||||
// loadActor 立即加载用户的实时权限快照;失败返回 nil(业务层按无权限处理)
|
||||
func (h *Handlers) loadActor(userID uint) *service.Actor {
|
||||
actor, err := h.Auth.LoadActor(userID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return actor
|
||||
}
|
||||
|
||||
// actorLoader 返回懒加载回调:仅当业务层确实需要实时权限快照
|
||||
// (访问待审内容等场景)时才查 DB
|
||||
func (h *Handlers) actorLoader(userID uint) func() *service.Actor {
|
||||
return func() *service.Actor {
|
||||
return h.loadActor(userID)
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,13 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ===== 用户管理(RequireAdmin 兜底,前端不做权限判定) =====
|
||||
// ===== 用户管理(RequireStaff + PermUsers 兜底,前端不做权限判定) =====
|
||||
|
||||
// AdminListUsers 用户分页列表(搜索/角色/状态筛选 + 全站汇总)
|
||||
func (h *Handlers) AdminListUsers(c *gin.Context) {
|
||||
@@ -39,27 +40,30 @@ func (h *Handlers) AdminListUsers(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// adminUserActionBody 角色/封禁变更的通用请求体
|
||||
type adminUserRoleBody struct {
|
||||
// adminStaffBody 角色与板块授权变更请求体
|
||||
type adminStaffBody struct {
|
||||
Role string `json:"role"`
|
||||
BoardIDs []uint `json:"board_ids"`
|
||||
}
|
||||
|
||||
type adminUserBanBody struct {
|
||||
Banned bool `json:"banned"`
|
||||
}
|
||||
|
||||
// AdminUpdateUserRole 设置用户角色(user / admin)
|
||||
// AdminUpdateUserRole 设置管理角色与板块授权
|
||||
func (h *Handlers) AdminUpdateUserRole(c *gin.Context) {
|
||||
id, ok := parseAdminUserID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body adminUserRoleBody
|
||||
var body adminStaffBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
user, err := h.AdminUser.SetRole(middleware.CurrentUser(c).ID, id, body.Role)
|
||||
user, err := h.AdminUser.SetStaff(
|
||||
middleware.CurrentActor(c), id, model.Role(body.Role), body.BoardIDs,
|
||||
)
|
||||
if err != nil {
|
||||
respondAdminUserError(c, err)
|
||||
return
|
||||
@@ -78,7 +82,7 @@ func (h *Handlers) AdminSetUserBan(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
user, err := h.AdminUser.SetBanned(middleware.CurrentUser(c).ID, id, body.Banned)
|
||||
user, err := h.AdminUser.SetBanned(middleware.CurrentActor(c), id, body.Banned)
|
||||
if err != nil {
|
||||
respondAdminUserError(c, err)
|
||||
return
|
||||
@@ -86,6 +90,21 @@ func (h *Handlers) AdminSetUserBan(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"user": user})
|
||||
}
|
||||
|
||||
// AdminUserLoginLogs 某用户的登录历史(IP/UA/成败)
|
||||
func (h *Handlers) AdminUserLoginLogs(c *gin.Context) {
|
||||
id, ok := parseAdminUserID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
logs, total, err := h.AdminUser.ListLoginLogs(id, page, 15)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取登录历史失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"logs": logs, "total": total, "page": page})
|
||||
}
|
||||
|
||||
// parseAdminUserID 解析路径中的用户 ID,失败时直接写出 400
|
||||
func parseAdminUserID(c *gin.Context) (uint, bool) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
@@ -101,9 +120,14 @@ func respondAdminUserError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
|
||||
case errors.Is(err, service.ErrProtectedOwner):
|
||||
// 站长保护属于权限边界而非参数错误
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrAdminSelfAction),
|
||||
errors.Is(err, service.ErrLastAdmin),
|
||||
errors.Is(err, service.ErrInvalidUserRole):
|
||||
errors.Is(err, service.ErrInvalidRole),
|
||||
errors.Is(err, service.ErrCannotAssignRole),
|
||||
errors.Is(err, service.ErrBoardRequired),
|
||||
errors.Is(err, service.ErrBoardNotFound):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "操作失败"})
|
||||
|
||||
@@ -21,6 +21,7 @@ var (
|
||||
// - refresh token(HttpOnly,7天,Path=/,供 Next middleware 在页面/RSC
|
||||
// 请求中读取并静默轮转;仅 /api/auth/refresh 端点消费)
|
||||
// - CSRF token(JS 可读,7天,双提交校验)
|
||||
//
|
||||
// SameSite=Lax:允许外站顶级链接进入时保留登录态(Strict 会导致从外站
|
||||
// 跳转进来的第一次请求丢 cookie,把已登录用户误判为游客);状态变更请求
|
||||
// 另有 CSRF 双提交 token 兜底。生产 HTTPS 下 cookie 名带 __Host- 前缀。
|
||||
@@ -127,6 +128,7 @@ func (h *Handlers) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
setAuthCookies(c, accessToken, refreshToken, !h.Cfg.DevMode)
|
||||
h.AdminUser.RecordLogin(loginUser.ID, req.Username, c.ClientIP(), c.Request.UserAgent(), true)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"user": gin.H{
|
||||
"id": loginUser.ID,
|
||||
@@ -147,6 +149,11 @@ func (h *Handlers) Login(c *gin.Context) {
|
||||
}
|
||||
accessToken, refreshToken, user, err := h.Auth.Login(req.Username, req.Password)
|
||||
if err != nil {
|
||||
// 登录失败也留痕:用户存在时带 user_id(封禁/错密),不存在时为 0
|
||||
h.AdminUser.RecordLogin(
|
||||
h.Auth.GetUserIDByUsername(req.Username), req.Username,
|
||||
c.ClientIP(), c.Request.UserAgent(), false,
|
||||
)
|
||||
// 封禁与凭据错误区分:前端可据此展示针对性提示
|
||||
if errors.Is(err, service.ErrAccountBanned) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error(), "code": "account_banned"})
|
||||
@@ -155,6 +162,8 @@ func (h *Handlers) Login(c *gin.Context) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 登录成功留痕(IP/UA/时间)
|
||||
h.AdminUser.RecordLogin(user.ID, req.Username, c.ClientIP(), c.Request.UserAgent(), true)
|
||||
// dev 模式不设 Secure,生产环境需 HTTPS
|
||||
setAuthCookies(c, accessToken, refreshToken, !h.Cfg.DevMode)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -232,8 +241,12 @@ func (h *Handlers) ChangePassword(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "密码修改成功,请重新登录"})
|
||||
}
|
||||
|
||||
// meUserBody 统一的用户信息响应体(Me/Login/Refresh 共用形状)
|
||||
func meUserBody(user *model.User) gin.H {
|
||||
// meUserBody 统一的用户信息响应体。boardIDs 为板块管理员被授权的板块,
|
||||
// 供前端渲染管理菜单与前台审核按钮;其他角色为空数组
|
||||
func meUserBody(user *model.User, boardIDs []uint) gin.H {
|
||||
if boardIDs == nil {
|
||||
boardIDs = []uint{}
|
||||
}
|
||||
return gin.H{
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
@@ -242,6 +255,7 @@ func meUserBody(user *model.User) gin.H {
|
||||
"signature": user.Signature,
|
||||
"email": user.Email,
|
||||
"role": user.Role,
|
||||
"board_ids": boardIDs,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,5 +282,10 @@ func (h *Handlers) Me(c *gin.Context) {
|
||||
if n, err := h.Notification.UnreadCount(claims.ID); err == nil {
|
||||
unread = n
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user": meUserBody(user), "unread_count": unread})
|
||||
// 板块管理员带出授权板块,供前端菜单/按钮按板块范围渲染
|
||||
var boardIDs []uint
|
||||
if user.Role == model.RoleBoardAdmin {
|
||||
boardIDs, _ = h.Auth.GetUserBoardIDs(claims.ID)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user": meUserBody(user, boardIDs), "unread_count": unread})
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -19,6 +21,18 @@ func (h *Handlers) PostComments(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||
|
||||
// 待审/被拒帖子的评论不对公众开放
|
||||
var viewerID uint
|
||||
var loadActor func() *service.Actor
|
||||
if claims := middleware.CurrentUser(c); claims != nil {
|
||||
viewerID = claims.ID
|
||||
loadActor = h.actorLoader(claims.ID)
|
||||
}
|
||||
if err := h.Post.EnsurePostVisible(uint(id), viewerID, loadActor); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
comments, floors, totalComments, err := h.Comment.ListFloorPaged(uint(id), page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
@@ -52,11 +66,17 @@ func (h *Handlers) CreateComment(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
comment, parent, err := h.Comment.Create(claims.ID, uint(id), req.Content, req.ParentID)
|
||||
// 管理团队成员评论免审;普通用户评论进入待审核队列,审核通过时才发业务通知
|
||||
status := model.ContentStatusPending
|
||||
if model.IsStaff(model.Role(claims.Role)) {
|
||||
status = model.ContentStatusPublished
|
||||
}
|
||||
comment, parent, err := h.Comment.Create(claims.ID, uint(id), req.Content, req.ParentID, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if comment.Status == model.ContentStatusPublished {
|
||||
if parent == nil {
|
||||
// 主评论:通知帖子作者(排除自己评论自己的帖子)
|
||||
if authorID, e := h.Post.GetAuthorID(uint(id)); e == nil {
|
||||
@@ -66,6 +86,7 @@ func (h *Handlers) CreateComment(c *gin.Context) {
|
||||
// 子回复:通知父评论作者(Notification.Create 内部排除自我通知)
|
||||
h.Notification.Create(parent.UserID, claims.ID, model.NotificationTypeReply, uint(id), comment.ID, req.Content)
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"comment": comment})
|
||||
}
|
||||
|
||||
@@ -77,8 +98,15 @@ func (h *Handlers) DeleteComment(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.Comment.Delete(uint(cid), claims.ID, claims.Role); err != nil {
|
||||
if err := h.Comment.Delete(h.loadActor(claims.ID), uint(cid), claims.ID); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrCommentNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrCommentForbidden):
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "已删除"})
|
||||
|
||||
@@ -20,4 +20,5 @@ type Handlers struct {
|
||||
Upload *service.UploadService
|
||||
Setting *service.SettingService
|
||||
AdminUser *service.AdminUserService
|
||||
Moderation *service.ModerationService
|
||||
}
|
||||
|
||||
85
backend/handler/moderation.go
Normal file
85
backend/handler/moderation.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ===== 内容审核队列(RequireStaff 基础鉴权,板块范围由 service 按 Actor 隔离) =====
|
||||
|
||||
// AdminPendingPosts 待审核帖子分页
|
||||
func (h *Handlers) AdminPendingPosts(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
posts, total, err := h.Moderation.PendingPosts(middleware.CurrentActor(c), page, 15)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取待审帖子失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"posts": posts, "total": total, "page": page})
|
||||
}
|
||||
|
||||
// AdminPendingComments 待审核评论分页
|
||||
func (h *Handlers) AdminPendingComments(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
comments, total, err := h.Moderation.PendingComments(middleware.CurrentActor(c), page, 15)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取待审评论失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"comments": comments, "total": total, "page": page})
|
||||
}
|
||||
|
||||
// AdminPendingCounts 当前操作者可见的待审数量(导航角标)
|
||||
func (h *Handlers) AdminPendingCounts(c *gin.Context) {
|
||||
posts, comments := h.Moderation.PendingCounts(middleware.CurrentActor(c))
|
||||
c.JSON(http.StatusOK, gin.H{"posts": posts, "comments": comments})
|
||||
}
|
||||
|
||||
// AdminApprovePost 通过帖子
|
||||
func (h *Handlers) AdminApprovePost(c *gin.Context) {
|
||||
h.execModeration(c, h.Moderation.ApprovePost)
|
||||
}
|
||||
|
||||
// AdminRejectPost 拒绝帖子
|
||||
func (h *Handlers) AdminRejectPost(c *gin.Context) {
|
||||
h.execModeration(c, h.Moderation.RejectPost)
|
||||
}
|
||||
|
||||
// AdminApproveComment 通过评论
|
||||
func (h *Handlers) AdminApproveComment(c *gin.Context) {
|
||||
h.execModeration(c, h.Moderation.ApproveComment)
|
||||
}
|
||||
|
||||
// AdminRejectComment 拒绝评论
|
||||
func (h *Handlers) AdminRejectComment(c *gin.Context) {
|
||||
h.execModeration(c, h.Moderation.RejectComment)
|
||||
}
|
||||
|
||||
// execModeration 统一解析 :id 并映射审核业务错误
|
||||
func (h *Handlers) execModeration(c *gin.Context, fn func(*service.Actor, uint) error) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的 ID"})
|
||||
return
|
||||
}
|
||||
if err := fn(middleware.CurrentActor(c), uint(id)); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "内容不存在"})
|
||||
case errors.Is(err, service.ErrModerationForbidden):
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrNotPending):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "操作失败"})
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "操作成功"})
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -56,13 +58,20 @@ func (h *Handlers) PostDetail(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的帖子 ID"})
|
||||
return
|
||||
}
|
||||
post, err := h.Post.GetByID(uint(id))
|
||||
claims := middleware.CurrentUser(c)
|
||||
var viewerID uint
|
||||
var loadActor func() *service.Actor
|
||||
if claims != nil {
|
||||
viewerID = claims.ID
|
||||
loadActor = h.actorLoader(claims.ID) // 懒加载:仅非已发布帖才查 DB
|
||||
}
|
||||
post, err := h.Post.GetByIDForViewer(uint(id), viewerID, loadActor)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
|
||||
return
|
||||
}
|
||||
// 填充点赞状态(仅登录用户)
|
||||
if claims := middleware.CurrentUser(c); claims != nil {
|
||||
if claims != nil {
|
||||
post.Liked = h.Like.HasLiked(post.ID, claims.ID)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"post": post})
|
||||
@@ -89,7 +98,13 @@ func (h *Handlers) CreatePost(c *gin.Context) {
|
||||
if postType == "" {
|
||||
postType = "normal"
|
||||
}
|
||||
post, err := h.Post.Create(claims.ID, req.BoardID, req.Title, req.Content, req.Tags, postType)
|
||||
// 管理团队成员发帖免审直发;普通用户进入待审核队列。
|
||||
// 角色变更会强制 JWT 失效(token_version 递增),claims.Role 可视为实时值
|
||||
status := model.ContentStatusPending
|
||||
if model.IsStaff(model.Role(claims.Role)) {
|
||||
status = model.ContentStatusPublished
|
||||
}
|
||||
post, err := h.Post.Create(claims.ID, req.BoardID, req.Title, req.Content, req.Tags, postType, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -117,9 +132,10 @@ func (h *Handlers) UpdatePost(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
post, err := h.Post.Update(uint(id), claims.ID, claims.Role, req.Title, req.Content, req.Tags)
|
||||
actor := h.loadActor(claims.ID)
|
||||
post, err := h.Post.Update(actor, uint(id), claims.ID, req.Title, req.Content, req.Tags)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
respondPostModError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"post": post})
|
||||
@@ -133,18 +149,16 @@ func (h *Handlers) DeletePost(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的帖子 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.Post.Delete(uint(id), claims.ID, claims.Role); err != nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
if err := h.Post.Delete(h.loadActor(claims.ID), uint(id), claims.ID); err != nil {
|
||||
respondPostModError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "已删除"})
|
||||
}
|
||||
|
||||
// TogglePin 切换帖子置顶(仅管理员)
|
||||
// TogglePin 切换帖子置顶(管理员及以上,板块管理员无此权限)
|
||||
func (h *Handlers) TogglePin(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims.Role != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "仅管理员可操作"})
|
||||
if !h.requireAdminOrAbove(c) {
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
@@ -160,11 +174,9 @@ func (h *Handlers) TogglePin(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"pinned": pinned})
|
||||
}
|
||||
|
||||
// ToggleRecommend 切换帖子推荐(仅管理员)
|
||||
// ToggleRecommend 切换帖子加精(管理员及以上,板块管理员无此权限)
|
||||
func (h *Handlers) ToggleRecommend(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims.Role != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "仅管理员可操作"})
|
||||
if !h.requireAdminOrAbove(c) {
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
@@ -179,3 +191,25 @@ func (h *Handlers) ToggleRecommend(c *gin.Context) {
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"recommended": recommended})
|
||||
}
|
||||
|
||||
// requireAdminOrAbove 置顶/加精仅管理员及以上可用;校验失败已写响应,返回 false
|
||||
func (h *Handlers) requireAdminOrAbove(c *gin.Context) bool {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if model.RoleLevel(model.Role(claims.Role)) < model.RoleLevel(model.RoleAdmin) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "仅管理员可操作"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// respondPostModError 帖子编辑/删除业务错误 → HTTP 状态码
|
||||
func respondPostModError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrPostNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrPostForbidden):
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -88,6 +89,12 @@ func (h *Handlers) UserProfile(c *gin.Context) {
|
||||
streak = cs.Streak
|
||||
}
|
||||
|
||||
// 板块管理员公开其授权板块(角色徽章展示"板块管理员 · 板块名")
|
||||
var boardIDs []uint
|
||||
if user.Role == model.RoleBoardAdmin {
|
||||
boardIDs, _ = h.Auth.GetUserBoardIDs(user.ID)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"user": gin.H{
|
||||
"id": user.ID,
|
||||
@@ -96,6 +103,7 @@ func (h *Handlers) UserProfile(c *gin.Context) {
|
||||
"avatar": user.Avatar,
|
||||
"signature": user.Signature,
|
||||
"role": user.Role,
|
||||
"board_ids": boardIDs,
|
||||
"created_at": user.CreatedAt,
|
||||
},
|
||||
"stats": gin.H{
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -59,7 +60,7 @@ func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// RequireAdmin 必须管理员
|
||||
// RequireAdmin 必须管理员(保留兼容;等价于"管理员及以上",不含纯板块管理员)
|
||||
func (m *AuthMiddleware) RequireAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
user, ok := m.parseToken(c)
|
||||
@@ -71,7 +72,7 @@ func (m *AuthMiddleware) RequireAdmin() gin.HandlerFunc {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
||||
return
|
||||
}
|
||||
if user.Role != service.RoleAdmin {
|
||||
if model.RoleLevel(model.Role(user.Role)) < model.RoleLevel(model.RoleAdmin) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "需要管理员权限"})
|
||||
return
|
||||
}
|
||||
@@ -80,6 +81,45 @@ func (m *AuthMiddleware) RequireAdmin() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// ActorKey 实时权限快照在 gin.Context 中的键
|
||||
const ActorKey = "actor"
|
||||
|
||||
// RequireStaff 必须是管理团队成员(板块管理员及以上),
|
||||
// 并把实时 Actor(角色+板块授权)写入 context 供 RequirePerm/handler 使用
|
||||
func (m *AuthMiddleware) RequireStaff() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims, ok := m.parseToken(c)
|
||||
if !ok {
|
||||
if c.GetBool(AccountBannedKey) {
|
||||
bannedJSON(c)
|
||||
return
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
||||
return
|
||||
}
|
||||
actor, err := m.auth.LoadActor(claims.ID)
|
||||
if err != nil || !actor.IsStaff() {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "需要管理员权限"})
|
||||
return
|
||||
}
|
||||
c.Set("user", claims)
|
||||
c.Set(ActorKey, actor)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequirePerm 功能点鉴权,必须接在 RequireStaff 之后
|
||||
func (m *AuthMiddleware) RequirePerm(perm string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
actor := CurrentActor(c)
|
||||
if !actor.HasPerm(perm) {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "无权限执行该操作"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// parseToken 解析并校验 token:
|
||||
// 1. 优先从 HttpOnly cookie 读取,回退 Authorization header
|
||||
// 2. 校验 JWT 签名和过期
|
||||
@@ -122,3 +162,13 @@ func CurrentUser(c *gin.Context) *service.UserClaims {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CurrentActor 从 context 获取当前操作者的实时权限快照(RequireStaff 写入)
|
||||
func CurrentActor(c *gin.Context) *service.Actor {
|
||||
if v, ok := c.Get(ActorKey); ok {
|
||||
if a, ok := v.(*service.Actor); ok {
|
||||
return a
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -31,11 +31,23 @@ func InitDB(dsn string) error {
|
||||
|
||||
if err := db.AutoMigrate(
|
||||
&User{}, &Board{}, &Post{}, &Comment{}, &RefreshToken{}, &Like{}, &Notification{}, &Checkin{},
|
||||
&Announcement{}, &SiteSetting{}, &Attachment{},
|
||||
&Announcement{}, &SiteSetting{}, &Attachment{}, &UserBoard{}, &LoginLog{},
|
||||
); err != nil {
|
||||
return fmt.Errorf("自动迁移失败: %w", err)
|
||||
}
|
||||
|
||||
// RBAC:把初始管理员(id 最小的 admin,通常即首个注册账号)升级为站长;
|
||||
// 已存在 owner 时不动数据,保证幂等
|
||||
if err := ensureOwnerRole(db); err != nil {
|
||||
return fmt.Errorf("站长角色迁移失败: %w", err)
|
||||
}
|
||||
|
||||
// login_logs.success 早期 default=true 与 GORM 零值省略叠加,
|
||||
// 会把失败登录错存为成功;AutoMigrate 不会改列默认值,这里幂等修正
|
||||
if err := db.Exec(`ALTER TABLE login_logs ALTER COLUMN success SET DEFAULT false`).Error; err != nil {
|
||||
return fmt.Errorf("login_logs 默认值修正失败: %w", err)
|
||||
}
|
||||
|
||||
// 新表结构就位后删除遗留的明文列
|
||||
if err := dropLegacyRefreshTokenColumn(db); err != nil {
|
||||
return fmt.Errorf("refresh token 旧列清理失败: %w", err)
|
||||
@@ -140,6 +152,31 @@ func dropLegacyRefreshTokenColumn(db *gorm.DB) error {
|
||||
return db.Exec(`ALTER TABLE refresh_tokens DROP COLUMN token`).Error
|
||||
}
|
||||
|
||||
// ensureOwnerRole 若无站长,则把 id 最小的旧管理员升级为站长;
|
||||
// 连管理员都没有的全新库,把 id=1 的初始账号设为站长
|
||||
func ensureOwnerRole(db *gorm.DB) error {
|
||||
var ownerCount int64
|
||||
if err := db.Model(&User{}).Where("role = ?", RoleOwner).Count(&ownerCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if ownerCount > 0 {
|
||||
return nil
|
||||
}
|
||||
res := db.Model(&User{}).Where("role = ?", RoleAdmin).
|
||||
Order("id ASC").Limit(1).Update("role", RoleOwner)
|
||||
if res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
if err := db.Model(&User{}).Order("id ASC").Limit(1).
|
||||
Update("role", RoleOwner).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
log.Println("[model] 已迁移初始账号为站长角色(owner)")
|
||||
return nil
|
||||
}
|
||||
|
||||
// seedDefaultBoards 写入默认板块
|
||||
func seedDefaultBoards(db *gorm.DB) {
|
||||
defaults := []Board{
|
||||
|
||||
@@ -6,14 +6,47 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Role 用户角色
|
||||
// Role 用户角色(等级递增:普通用户 < 板块管理员 < 管理员 < 超级管理员 < 站长)
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleUser Role = "user"
|
||||
RoleAdmin Role = "admin"
|
||||
RoleUser Role = "user" // 普通用户:发帖/评论需审核
|
||||
RoleBoardAdmin Role = "board_admin" // 板块管理员:仅管理被授权板块的帖子与评论
|
||||
RoleAdmin Role = "admin" // 管理员:公告 + 全站帖子/评论审核
|
||||
RoleSuperAdmin Role = "super_admin" // 超级管理员:全站后台(用户/公告/设置/内容),但不可操作站长
|
||||
RoleOwner Role = "owner" // 站长:最高权限,全站唯一,任何人(含自己)不可改角色/封禁
|
||||
)
|
||||
|
||||
// RoleLevel 角色等级,用于层级比较;未知角色按普通用户处理
|
||||
func RoleLevel(r Role) int {
|
||||
switch r {
|
||||
case RoleOwner:
|
||||
return 100
|
||||
case RoleSuperAdmin:
|
||||
return 80
|
||||
case RoleAdmin:
|
||||
return 50
|
||||
case RoleBoardAdmin:
|
||||
return 30
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// IsStaff 是否为任一管理角色(板块管理员及以上)
|
||||
func IsStaff(r Role) bool {
|
||||
return RoleLevel(r) >= RoleLevel(RoleBoardAdmin)
|
||||
}
|
||||
|
||||
// ValidRole 角色枚举校验
|
||||
func ValidRole(r Role) bool {
|
||||
switch r {
|
||||
case RoleUser, RoleBoardAdmin, RoleAdmin, RoleSuperAdmin, RoleOwner:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 内容审核状态
|
||||
const (
|
||||
ContentStatusPending = "pending"
|
||||
@@ -139,6 +172,8 @@ const (
|
||||
NotificationTypeComment = "comment" // 评论了你的帖子
|
||||
NotificationTypeReply = "reply" // 回复了你的评论
|
||||
NotificationTypeLike = "like" // 点赞了你的帖子
|
||||
NotificationTypeApproved = "approved" // 内容审核通过
|
||||
NotificationTypeRejected = "rejected" // 内容审核未通过
|
||||
)
|
||||
|
||||
// Notification 站内通知
|
||||
@@ -195,3 +230,25 @@ type Attachment struct {
|
||||
Height int `gorm:"not null;default:0" json:"height"`
|
||||
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
||||
}
|
||||
|
||||
// UserBoard 板块管理员的板块授权(多对多;仅 role=board_admin 的行生效)
|
||||
type UserBoard struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"uniqueIndex:idx_user_board;not null" json:"user_id"`
|
||||
BoardID uint `gorm:"uniqueIndex:idx_user_board;not null" json:"board_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
User User `gorm:"foreignKey:UserID" json:"-"`
|
||||
Board Board `gorm:"foreignKey:BoardID" json:"board,omitempty"`
|
||||
}
|
||||
|
||||
// LoginLog 登录历史(成功与失败都记录;失败时用户名可能不存在,UserID 为 0)
|
||||
type LoginLog struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"index;not null;default:0" json:"user_id"`
|
||||
Username string `gorm:"size:128;index;not null;default:''" json:"username"`
|
||||
IP string `gorm:"size:45;not null;default:''" json:"ip"` // IPv4/IPv6 最长 45 字符
|
||||
UserAgent string `gorm:"size:512;not null;default:''" json:"user_agent"`
|
||||
Success bool `gorm:"index;not null;default:false" json:"success"`
|
||||
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
uploadSvc := service.NewUploadService(model.DB, filepath.Join(cfg.DataDir, "uploads"))
|
||||
settingSvc := service.NewSettingService(model.DB)
|
||||
adminUserSvc := service.NewAdminUserService(model.DB)
|
||||
moderationSvc := service.NewModerationService(model.DB, notifSvc)
|
||||
if err := uploadSvc.EnsureDir(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -69,6 +70,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
Upload: uploadSvc,
|
||||
Setting: settingSvc,
|
||||
AdminUser: adminUserSvc,
|
||||
Moderation: moderationSvc,
|
||||
}
|
||||
|
||||
authMW := middleware.NewAuthMiddleware(authSvc)
|
||||
@@ -131,23 +133,39 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
api.DELETE("/my/attachments/:id", h.DeleteAttachment)
|
||||
}
|
||||
|
||||
// 管理员 API(同样需要 CSRF 防护)
|
||||
adminAPI := r.Group("/api/admin", authMW.RequireAuth(), middleware.CSRFMiddleware(), authMW.RequireAdmin())
|
||||
// 管理后台 API:RequireStaff 基础鉴权(板块管理员及以上,Actor 实时从 DB 现取),
|
||||
// 各功能点再由 RequirePerm 按角色放行;板块范围在 service 层按 Actor.BoardIDs 隔离
|
||||
staffAPI := r.Group("/api/admin", authMW.RequireStaff(), middleware.CSRFMiddleware())
|
||||
{
|
||||
adminAPI.GET("/dashboard", func(c *gin.Context) {
|
||||
staffAPI.GET("/dashboard", func(c *gin.Context) {
|
||||
c.JSON(200, gin.H{"message": "admin dashboard"})
|
||||
})
|
||||
// 站点公告文章管理
|
||||
adminAPI.GET("/announcements", h.AdminListAnnouncements)
|
||||
adminAPI.POST("/announcements", h.AdminCreateAnnouncement)
|
||||
adminAPI.PUT("/announcements/:id", h.AdminUpdateAnnouncement)
|
||||
adminAPI.DELETE("/announcements/:id", h.AdminDeleteAnnouncement)
|
||||
// 站点外观设置(主题色)
|
||||
adminAPI.PUT("/settings", h.UpdateSettings)
|
||||
// 用户管理:列表(搜索/筛选/汇总)、角色变更、封禁解封
|
||||
adminAPI.GET("/users", h.AdminListUsers)
|
||||
adminAPI.PUT("/users/:id/role", h.AdminUpdateUserRole)
|
||||
adminAPI.PUT("/users/:id/ban", h.AdminSetUserBan)
|
||||
|
||||
// 内容审核队列(任意管理角色;板块管理员只见授权板块)
|
||||
staffAPI.GET("/moderation/pending-posts", h.AdminPendingPosts)
|
||||
staffAPI.GET("/moderation/pending-comments", h.AdminPendingComments)
|
||||
staffAPI.GET("/moderation/counts", h.AdminPendingCounts)
|
||||
staffAPI.PUT("/moderation/posts/:id/approve", h.AdminApprovePost)
|
||||
staffAPI.PUT("/moderation/posts/:id/reject", h.AdminRejectPost)
|
||||
staffAPI.PUT("/moderation/comments/:id/approve", h.AdminApproveComment)
|
||||
staffAPI.PUT("/moderation/comments/:id/reject", h.AdminRejectComment)
|
||||
|
||||
// 站点公告文章管理(管理员及以上)
|
||||
announceAPI := staffAPI.Group("", authMW.RequirePerm(service.PermAnnouncements))
|
||||
announceAPI.GET("/announcements", h.AdminListAnnouncements)
|
||||
announceAPI.POST("/announcements", h.AdminCreateAnnouncement)
|
||||
announceAPI.PUT("/announcements/:id", h.AdminUpdateAnnouncement)
|
||||
announceAPI.DELETE("/announcements/:id", h.AdminDeleteAnnouncement)
|
||||
|
||||
// 站点外观设置(超级管理员/站长)
|
||||
staffAPI.PUT("/settings", authMW.RequirePerm(service.PermSettings), h.UpdateSettings)
|
||||
|
||||
// 用户与权限管理(超级管理员/站长):列表、角色授权、封禁、登录历史
|
||||
usersAPI := staffAPI.Group("", authMW.RequirePerm(service.PermUsers))
|
||||
usersAPI.GET("/users", h.AdminListUsers)
|
||||
usersAPI.PUT("/users/:id/role", h.AdminUpdateUserRole)
|
||||
usersAPI.PUT("/users/:id/ban", h.AdminSetUserBan)
|
||||
usersAPI.GET("/users/:id/login-logs", h.AdminUserLoginLogs)
|
||||
}
|
||||
|
||||
r.NoRoute(func(c *gin.Context) {
|
||||
|
||||
115
backend/service/actor.go
Normal file
115
backend/service/actor.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
)
|
||||
|
||||
// 权限码:后台功能点。路由通过 RequirePerm 声明,
|
||||
// 板块管理员的板块范围由 Actor.BoardIDs 在业务层二次校验。
|
||||
const (
|
||||
PermUsers = "users" // 用户与权限管理(超管/站长)
|
||||
PermAnnouncements = "announcements" // 公告管理(管理员及以上)
|
||||
PermSettings = "settings" // 站点外观设置(超管/站长)
|
||||
PermModeration = "moderation" // 内容审核(任意管理角色,板块范围受限)
|
||||
)
|
||||
|
||||
// Actor 当前请求操作者的实时权限快照(每次后台请求从 DB 现取,
|
||||
// 不依赖 JWT 内的 role claim,角色/授权变更立即生效)
|
||||
type Actor struct {
|
||||
ID uint
|
||||
Username string
|
||||
Role model.Role
|
||||
BoardIDs []uint // 板块管理员被授权的板块;其他角色为空
|
||||
}
|
||||
|
||||
// IsStaff 是否管理团队成员
|
||||
func (a *Actor) IsStaff() bool {
|
||||
return a != nil && model.IsStaff(a.Role)
|
||||
}
|
||||
|
||||
// HasPerm 是否拥有某后台功能点
|
||||
func (a *Actor) HasPerm(p string) bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
switch p {
|
||||
case PermUsers, PermSettings:
|
||||
return a.Role == model.RoleSuperAdmin || a.Role == model.RoleOwner
|
||||
case PermAnnouncements:
|
||||
return model.RoleLevel(a.Role) >= model.RoleLevel(model.RoleAdmin)
|
||||
case PermModeration:
|
||||
return a.IsStaff()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CanModerateBoard 是否可管理指定板块的内容:
|
||||
// 管理员及以上不限板块;板块管理员仅限被授权板块
|
||||
func (a *Actor) CanModerateBoard(boardID uint) bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
if model.RoleLevel(a.Role) >= model.RoleLevel(model.RoleAdmin) {
|
||||
return true
|
||||
}
|
||||
if a.Role != model.RoleBoardAdmin {
|
||||
return false
|
||||
}
|
||||
for _, id := range a.BoardIDs {
|
||||
if id == boardID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CanAssignRole 操作者能否把他人设置为目标角色(站长不可被授予,仅站长可授予超管)
|
||||
func (a *Actor) CanAssignRole(target model.Role) bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
if target == model.RoleOwner {
|
||||
return false // 站长身份不通过授权产生
|
||||
}
|
||||
if target == model.RoleSuperAdmin {
|
||||
return a.Role == model.RoleOwner
|
||||
}
|
||||
return a.HasPerm(PermUsers)
|
||||
}
|
||||
|
||||
// LoadActor 读取用户实时角色与板块授权
|
||||
func (s *AuthService) LoadActor(id uint) (*Actor, error) {
|
||||
var u model.User
|
||||
if err := s.db.Select("id", "username", "role").First(&u, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
actor := &Actor{ID: u.ID, Username: u.Username, Role: u.Role, BoardIDs: []uint{}}
|
||||
if u.Role == model.RoleBoardAdmin {
|
||||
var ids []uint
|
||||
if err := s.db.Model(&model.UserBoard{}).
|
||||
Where("user_id = ?", id).
|
||||
Order("board_id ASC").
|
||||
Pluck("board_id", &ids).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
actor.BoardIDs = ids
|
||||
}
|
||||
return actor, nil
|
||||
}
|
||||
|
||||
// GetUserBoardIDs 读取用户被授权的板块 ID(供 /me 等场景)
|
||||
func (s *AuthService) GetUserBoardIDs(id uint) ([]uint, error) {
|
||||
var ids []uint
|
||||
err := s.db.Model(&model.UserBoard{}).
|
||||
Where("user_id = ?", id).Order("board_id ASC").Pluck("board_id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
// GetUserIDByUsername 按用户名查 ID(登录失败审计用),用户不存在返回 0
|
||||
func (s *AuthService) GetUserIDByUsername(username string) uint {
|
||||
var u model.User
|
||||
if err := s.db.Select("id").Where("username = ?", username).First(&u).Error; err != nil {
|
||||
return 0
|
||||
}
|
||||
return u.ID
|
||||
}
|
||||
@@ -8,16 +8,25 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 管理员用户操作的业务护栏(handler 层映射为 400,前端只展示消息)
|
||||
// 管理员用户操作的业务护栏(handler 层映射为 4xx,前端只展示消息)
|
||||
var (
|
||||
// ErrAdminSelfAction 不能对自己的账号执行管理操作(自锁/误操作保护)
|
||||
ErrAdminSelfAction = errors.New("不能对自己的账号执行该操作")
|
||||
// ErrLastAdmin 至少保留一名未封禁的管理员,防止站点失去管理入口
|
||||
ErrLastAdmin = errors.New("至少保留一名未封禁的管理员")
|
||||
// ErrInvalidUserRole 角色入参非法
|
||||
ErrInvalidUserRole = errors.New("角色参数无效")
|
||||
// ErrInvalidRole 角色入参非法
|
||||
ErrInvalidRole = errors.New("角色参数无效")
|
||||
// ErrProtectedOwner 站长账号受保护,任何人不可改角色/封禁
|
||||
ErrProtectedOwner = errors.New("站长账号受保护,不可操作")
|
||||
// ErrCannotAssignRole 当前操作者无权授予该角色
|
||||
ErrCannotAssignRole = errors.New("无权授予该角色")
|
||||
// ErrBoardRequired 板块管理员至少要授权一个板块
|
||||
ErrBoardRequired = errors.New("板块管理员至少需要授权一个板块")
|
||||
// ErrBoardNotFound 授权的板块不存在
|
||||
ErrBoardNotFound = errors.New("部分板块不存在")
|
||||
)
|
||||
|
||||
// onlineThreshold last_seen_at 在该窗口内视为在线
|
||||
const onlineThreshold = 5 * time.Minute
|
||||
|
||||
// AdminUserService 后台用户管理
|
||||
type AdminUserService struct {
|
||||
db *gorm.DB
|
||||
@@ -27,7 +36,7 @@ func NewAdminUserService(db *gorm.DB) *AdminUserService {
|
||||
return &AdminUserService{db: db}
|
||||
}
|
||||
|
||||
// AdminUserItem 后台用户列表项:email / last_seen 在 User 模型上 json:"-",
|
||||
// AdminUserItem 后台用户列表项:email / last_seen / 登录 IP 在 User 模型上 json:"-",
|
||||
// 仅管理员接口通过此 DTO 显式带出
|
||||
type AdminUserItem struct {
|
||||
ID uint `json:"id"`
|
||||
@@ -37,14 +46,18 @@ type AdminUserItem struct {
|
||||
Avatar string `json:"avatar"`
|
||||
Signature string `json:"signature"`
|
||||
Role string `json:"role"`
|
||||
BoardIDs []uint `json:"board_ids"`
|
||||
Banned bool `json:"banned"`
|
||||
PostCount int64 `json:"post_count"`
|
||||
CommentCount int64 `json:"comment_count"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastSeenAt *time.Time `json:"last_seen_at"`
|
||||
Online bool `json:"online"`
|
||||
LastLoginIP string `json:"last_login_ip"`
|
||||
LastLoginAt *time.Time `json:"last_login_at"`
|
||||
}
|
||||
|
||||
// AdminUserSummary 列表顶部汇总(总数/管理员/封禁/今日新增)
|
||||
// AdminUserSummary 列表顶部汇总(总数/管理团队/封禁/今日新增)
|
||||
type AdminUserSummary struct {
|
||||
Total int64 `json:"total"`
|
||||
Admins int64 `json:"admins"`
|
||||
@@ -52,12 +65,18 @@ type AdminUserSummary struct {
|
||||
TodayNew int64 `json:"today_new"`
|
||||
}
|
||||
|
||||
// staffRoles 管理团队角色集合
|
||||
var staffRoles = []string{
|
||||
string(model.RoleBoardAdmin), string(model.RoleAdmin),
|
||||
string(model.RoleSuperAdmin), string(model.RoleOwner),
|
||||
}
|
||||
|
||||
// AdminUserListQuery 用户列表查询
|
||||
type AdminUserListQuery struct {
|
||||
Page int
|
||||
Size int
|
||||
Keyword string // 用户名 / 昵称 / 邮箱模糊匹配
|
||||
Role string // "" 全部 | "admin" 仅管理员
|
||||
Role string // "" 全部 | "staff" 管理团队 | 具体角色枚举
|
||||
Status string // "" 全部 | "banned" 已封禁 | "normal" 正常
|
||||
}
|
||||
|
||||
@@ -84,8 +103,11 @@ func (s *AdminUserService) List(q AdminUserListQuery) (*AdminUserListResult, err
|
||||
like := "%" + kw + "%"
|
||||
query = query.Where("username ILIKE ? OR nickname ILIKE ? OR email ILIKE ?", like, like, like)
|
||||
}
|
||||
if q.Role == string(model.RoleAdmin) {
|
||||
query = query.Where("role = ?", model.RoleAdmin)
|
||||
switch {
|
||||
case q.Role == "staff":
|
||||
query = query.Where("role IN ?", staffRoles)
|
||||
case q.Role != "" && model.ValidRole(model.Role(q.Role)):
|
||||
query = query.Where("role = ?", q.Role)
|
||||
}
|
||||
if q.Status == "banned" {
|
||||
query = query.Where("banned = ?", true)
|
||||
@@ -112,7 +134,7 @@ func (s *AdminUserService) List(q AdminUserListQuery) (*AdminUserListResult, err
|
||||
dayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
summary := AdminUserSummary{}
|
||||
s.db.Model(&model.User{}).Count(&summary.Total)
|
||||
s.db.Model(&model.User{}).Where("role = ?", model.RoleAdmin).Count(&summary.Admins)
|
||||
s.db.Model(&model.User{}).Where("role IN ?", staffRoles).Count(&summary.Admins)
|
||||
s.db.Model(&model.User{}).Where("banned = ?", true).Count(&summary.Banned)
|
||||
s.db.Model(&model.User{}).Where("created_at >= ?", dayStart).Count(&summary.TodayNew)
|
||||
|
||||
@@ -125,13 +147,14 @@ func (s *AdminUserService) List(q AdminUserListQuery) (*AdminUserListResult, err
|
||||
}, nil
|
||||
}
|
||||
|
||||
// toItems 批量把 User 模型转为 DTO,并用两条 GROUP BY 填充计数
|
||||
// toItems 批量把 User 模型转为 DTO,并用聚合查询填充计数/授权板块/最近登录
|
||||
func (s *AdminUserService) toItems(users []model.User) []AdminUserItem {
|
||||
items := make([]AdminUserItem, 0, len(users))
|
||||
ids := make([]uint, 0, len(users))
|
||||
now := time.Now()
|
||||
for _, u := range users {
|
||||
ids = append(ids, u.ID)
|
||||
items = append(items, AdminUserItem{
|
||||
item := AdminUserItem{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
Nickname: u.Nickname,
|
||||
@@ -139,15 +162,33 @@ func (s *AdminUserService) toItems(users []model.User) []AdminUserItem {
|
||||
Avatar: u.Avatar,
|
||||
Signature: u.Signature,
|
||||
Role: string(u.Role),
|
||||
BoardIDs: []uint{},
|
||||
Banned: u.Banned,
|
||||
CreatedAt: u.CreatedAt,
|
||||
LastSeenAt: u.LastSeenAt,
|
||||
})
|
||||
}
|
||||
if u.LastSeenAt != nil && now.Sub(*u.LastSeenAt) <= onlineThreshold {
|
||||
item.Online = true
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return items
|
||||
}
|
||||
|
||||
// 板块授权:一次查出本页全部映射
|
||||
type ubRow struct {
|
||||
UserID uint
|
||||
BoardID uint
|
||||
}
|
||||
var ubRows []ubRow
|
||||
s.db.Model(&model.UserBoard{}).Where("user_id IN ?", ids).
|
||||
Order("board_id ASC").Scan(&ubRows)
|
||||
boardsMap := map[uint][]uint{}
|
||||
for _, r := range ubRows {
|
||||
boardsMap[r.UserID] = append(boardsMap[r.UserID], r.BoardID)
|
||||
}
|
||||
|
||||
type countRow struct {
|
||||
UserID uint
|
||||
Cnt int64
|
||||
@@ -173,9 +214,32 @@ func (s *AdminUserService) toItems(users []model.User) []AdminUserItem {
|
||||
commentCounts[r.UserID] = r.Cnt
|
||||
}
|
||||
|
||||
// 每个用户最近一次成功登录(DISTINCT ON 走 user_id+created_at 索引)
|
||||
type loginRow struct {
|
||||
UserID uint
|
||||
IP string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
var loginRows []loginRow
|
||||
s.db.Raw(`SELECT DISTINCT ON (user_id) user_id, ip, created_at
|
||||
FROM login_logs WHERE user_id IN ? AND success = true
|
||||
ORDER BY user_id, created_at DESC`, ids).Scan(&loginRows)
|
||||
lastLogin := map[uint]loginRow{}
|
||||
for _, r := range loginRows {
|
||||
lastLogin[r.UserID] = r
|
||||
}
|
||||
|
||||
for i := range items {
|
||||
items[i].PostCount = postCounts[items[i].ID]
|
||||
items[i].CommentCount = commentCounts[items[i].ID]
|
||||
if b := boardsMap[items[i].ID]; len(b) > 0 {
|
||||
items[i].BoardIDs = b
|
||||
}
|
||||
if l, ok := lastLogin[items[i].ID]; ok {
|
||||
t := l.CreatedAt
|
||||
items[i].LastLoginIP = l.IP
|
||||
items[i].LastLoginAt = &t
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -190,42 +254,78 @@ func (s *AdminUserService) getItem(tx *gorm.DB, id uint) (*AdminUserItem, error)
|
||||
return &items[0], nil
|
||||
}
|
||||
|
||||
// SetRole 修改用户角色。管理员降级时递增 token_version 并撤销 refresh token,
|
||||
// 使其旧 JWT(claims 中仍带 admin)立即失效,需重新登录获得新角色身份
|
||||
func (s *AdminUserService) SetRole(operatorID, targetID uint, role string) (*AdminUserItem, error) {
|
||||
if role != string(model.RoleAdmin) && role != string(model.RoleUser) {
|
||||
return nil, ErrInvalidUserRole
|
||||
// SetStaff 修改用户管理角色与板块授权。角色变更后强制下线,
|
||||
// 使其旧 JWT(claims 中带旧角色)立即失效,需重新登录获得新身份。
|
||||
// 站长账号任何时候都不可被操作;只有站长可授予超管;站长身份不可被授予。
|
||||
func (s *AdminUserService) SetStaff(operator *Actor, targetID uint, role model.Role, boardIDs []uint) (*AdminUserItem, error) {
|
||||
if operator == nil {
|
||||
return nil, ErrCannotAssignRole
|
||||
}
|
||||
if operatorID == targetID {
|
||||
if operator.ID == targetID {
|
||||
return nil, ErrAdminSelfAction
|
||||
}
|
||||
if !model.ValidRole(role) || role == model.RoleOwner {
|
||||
return nil, ErrInvalidRole
|
||||
}
|
||||
if !operator.CanAssignRole(role) {
|
||||
return nil, ErrCannotAssignRole
|
||||
}
|
||||
|
||||
// 板块管理员:规整、去重并校验板块存在
|
||||
var normBoards []uint
|
||||
if role == model.RoleBoardAdmin {
|
||||
seen := map[uint]bool{}
|
||||
for _, b := range boardIDs {
|
||||
if b > 0 && !seen[b] {
|
||||
seen[b] = true
|
||||
normBoards = append(normBoards, b)
|
||||
}
|
||||
}
|
||||
if len(normBoards) == 0 {
|
||||
return nil, ErrBoardRequired
|
||||
}
|
||||
var boardCnt int64
|
||||
if err := s.db.Model(&model.Board{}).Where("id IN ?", normBoards).Count(&boardCnt).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int(boardCnt) != len(normBoards) {
|
||||
return nil, ErrBoardNotFound
|
||||
}
|
||||
}
|
||||
|
||||
var item *AdminUserItem
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var u model.User
|
||||
if err := tx.First(&u, targetID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if string(u.Role) == role {
|
||||
return nil
|
||||
// 站长账号是唯一硬保护对象
|
||||
if u.Role == model.RoleOwner {
|
||||
return ErrProtectedOwner
|
||||
}
|
||||
// 降级管理员:确保还存在另一名未封禁管理员
|
||||
if u.Role == model.RoleAdmin {
|
||||
var otherAdmins int64
|
||||
if err := tx.Model(&model.User{}).
|
||||
Where("role = ? AND banned = ? AND id <> ?", model.RoleAdmin, false, targetID).
|
||||
Count(&otherAdmins).Error; err != nil {
|
||||
|
||||
roleChanged := u.Role != role
|
||||
if roleChanged {
|
||||
if err := tx.Model(&u).Update("role", role).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if otherAdmins == 0 {
|
||||
return ErrLastAdmin
|
||||
}
|
||||
}
|
||||
if err := tx.Model(&u).Update("role", model.Role(role)).Error; err != nil {
|
||||
|
||||
// 同步板块授权:整体替换;非板块管理员清空
|
||||
if err := tx.Where("user_id = ?", targetID).Delete(&model.UserBoard{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 管理员被降级:强制下线,避免 15 分钟 JWT 窗口内仍保有管理权限
|
||||
if role == string(model.RoleUser) {
|
||||
if role == model.RoleBoardAdmin {
|
||||
rows := make([]model.UserBoard, 0, len(normBoards))
|
||||
for _, b := range normBoards {
|
||||
rows = append(rows, model.UserBoard{UserID: targetID, BoardID: b})
|
||||
}
|
||||
if err := tx.Create(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 任何角色变化都强制下线(板块授权变化因 Actor 每次现查 DB,无需下线)
|
||||
if roleChanged {
|
||||
if err := invalidateUserSessions(tx, targetID); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -235,13 +335,15 @@ func (s *AdminUserService) SetRole(operatorID, targetID uint, role string) (*Adm
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item, err = s.getItem(s.db, targetID)
|
||||
return item, err
|
||||
return s.getItem(s.db, targetID)
|
||||
}
|
||||
|
||||
// SetBanned 封禁/解封用户。封禁时同事务使该用户全部登录态立即失效
|
||||
func (s *AdminUserService) SetBanned(operatorID, targetID uint, banned bool) (*AdminUserItem, error) {
|
||||
if operatorID == targetID {
|
||||
// SetBanned 封禁/解封用户。站长账号不可封禁;封禁时同事务使登录态立即失效
|
||||
func (s *AdminUserService) SetBanned(operator *Actor, targetID uint, banned bool) (*AdminUserItem, error) {
|
||||
if operator == nil {
|
||||
return nil, ErrProtectedOwner
|
||||
}
|
||||
if operator.ID == targetID {
|
||||
return nil, ErrAdminSelfAction
|
||||
}
|
||||
|
||||
@@ -250,21 +352,12 @@ func (s *AdminUserService) SetBanned(operatorID, targetID uint, banned bool) (*A
|
||||
if err := tx.First(&u, targetID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if u.Role == model.RoleOwner {
|
||||
return ErrProtectedOwner
|
||||
}
|
||||
if u.Banned == banned {
|
||||
return nil
|
||||
}
|
||||
// 封禁管理员:确保还存在另一名未封禁管理员,避免站点失去管理入口
|
||||
if banned && u.Role == model.RoleAdmin {
|
||||
var otherAdmins int64
|
||||
if err := tx.Model(&model.User{}).
|
||||
Where("role = ? AND banned = ? AND id <> ?", model.RoleAdmin, false, targetID).
|
||||
Count(&otherAdmins).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if otherAdmins == 0 {
|
||||
return ErrLastAdmin
|
||||
}
|
||||
}
|
||||
if err := tx.Model(&u).Update("banned", banned).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -281,6 +374,55 @@ func (s *AdminUserService) SetBanned(operatorID, targetID uint, banned bool) (*A
|
||||
return s.getItem(s.db, targetID)
|
||||
}
|
||||
|
||||
// RecordLogin 记录一次登录尝试(成功/失败都写)。失败时用户可能不存在,
|
||||
// userID 传 0,username 仍落库便于异常登录排查
|
||||
func (s *AdminUserService) RecordLogin(userID uint, username, ip, ua string, success bool) {
|
||||
if len([]rune(ua)) > 500 {
|
||||
ua = string([]rune(ua)[:500])
|
||||
}
|
||||
log := model.LoginLog{
|
||||
UserID: userID,
|
||||
Username: truncateStr(username, 128),
|
||||
IP: truncateStr(ip, 45),
|
||||
UserAgent: ua,
|
||||
Success: success,
|
||||
}
|
||||
// Select 强制写入全部字段:Success=false 是 Go 零值,
|
||||
// 否则 GORM 会因 default 标签省略该列,导致失败记录被写成默认值
|
||||
_ = s.db.Select("user_id", "username", "ip", "user_agent", "success", "created_at").
|
||||
Create(&log).Error // 审计写失败不应阻断登录
|
||||
}
|
||||
|
||||
// ListLoginLogs 查询某用户的登录历史(最近在前)
|
||||
func (s *AdminUserService) ListLoginLogs(targetID uint, page, size int) ([]model.LoginLog, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 50 {
|
||||
size = 15
|
||||
}
|
||||
q := s.db.Model(&model.LoginLog{}).Where("user_id = ?", targetID)
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var logs []model.LoginLog
|
||||
if err := q.Order("created_at DESC").
|
||||
Offset((page - 1) * size).Limit(size).
|
||||
Find(&logs).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return logs, total, nil
|
||||
}
|
||||
|
||||
func truncateStr(s string, n int) string {
|
||||
r := []rune(s)
|
||||
if len(r) > n {
|
||||
return string(r[:n])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// invalidateUserSessions 在事务内递增 token_version 并撤销全部 refresh token,
|
||||
// 与 AuthService 的强制下线逻辑等价(封禁/管理员降级时调用)
|
||||
func invalidateUserSessions(tx *gorm.DB, userID uint) error {
|
||||
|
||||
@@ -21,9 +21,6 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
RoleUser = "user"
|
||||
RoleAdmin = "admin"
|
||||
|
||||
// CSRFHeaderName 前端传递 CSRF token 的 header 名
|
||||
CSRFHeaderName = "X-CSRF-Token"
|
||||
|
||||
|
||||
@@ -9,6 +9,12 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 评论操作错误
|
||||
var (
|
||||
ErrCommentNotFound = errors.New("评论不存在")
|
||||
ErrCommentForbidden = errors.New("无权限删除此评论")
|
||||
)
|
||||
|
||||
// CommentService 评论服务
|
||||
type CommentService struct {
|
||||
db *gorm.DB
|
||||
@@ -114,25 +120,33 @@ func (s *CommentService) ListFloorPaged(postID uint, page, size int) ([]CommentN
|
||||
return result, floors, totalComments, nil
|
||||
}
|
||||
|
||||
// Create 创建评论(parentID 为 nil 时发主评论/楼层,否则发为对应评论的子回复)
|
||||
// Create 创建评论(parentID 为 nil 时发主评论/楼层,否则发为对应评论的子回复)。
|
||||
// status 由 handler 按角色计算:管理团队直发 published,普通用户进入 pending;
|
||||
// pending 评论不计入 comment_count,审核通过时才 +1。
|
||||
// 返回:新评论、父评论(子回复时非 nil,供通知定位被回复人)
|
||||
func (s *CommentService) Create(userID, postID uint, content string, parentID *uint) (*model.Comment, *model.Comment, error) {
|
||||
func (s *CommentService) Create(userID, postID uint, content string, parentID *uint, status string) (*model.Comment, *model.Comment, error) {
|
||||
content = strings.TrimSpace(content)
|
||||
if content == "" {
|
||||
return nil, nil, errors.New("评论内容不能为空")
|
||||
}
|
||||
if status != model.ContentStatusPending && status != model.ContentStatusPublished {
|
||||
status = model.ContentStatusPending
|
||||
}
|
||||
|
||||
// 检查帖子是否存在且未锁定评论
|
||||
// 检查帖子存在且已发布(待审/被拒帖子不接受评论)
|
||||
var post model.Post
|
||||
if err := s.db.First(&post, postID).Error; err != nil {
|
||||
return nil, nil, errors.New("帖子不存在")
|
||||
}
|
||||
if post.Status != model.ContentStatusPublished {
|
||||
return nil, nil, errors.New("帖子不存在")
|
||||
}
|
||||
|
||||
comment := &model.Comment{
|
||||
PostID: postID,
|
||||
UserID: userID,
|
||||
Content: content,
|
||||
Status: model.ContentStatusPublished,
|
||||
Status: status,
|
||||
}
|
||||
|
||||
// 子回复:校验父评论(同帖、已发布),继承楼层根与层级
|
||||
@@ -159,8 +173,10 @@ func (s *CommentService) Create(userID, postID uint, content string, parentID *u
|
||||
if err := s.db.Create(comment).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// 更新帖子评论数
|
||||
// 仅已发布评论立即计入评论数;待审评论通过审核时才 +1
|
||||
if comment.Status == model.ContentStatusPublished {
|
||||
s.db.Model(&post).UpdateColumn("comment_count", gorm.Expr("comment_count + 1"))
|
||||
}
|
||||
// 预加载用户
|
||||
s.db.Preload("User").First(comment, comment.ID)
|
||||
return comment, parent, nil
|
||||
@@ -210,15 +226,22 @@ func (s *CommentService) CountByUser(userID uint) (int64, error) {
|
||||
return total, err
|
||||
}
|
||||
|
||||
// Delete 删除评论(仅作者或管理员可操作),级联软删整棵子树
|
||||
func (s *CommentService) Delete(commentID, userID uint, role string) error {
|
||||
// Delete 删除评论(作者本人,或对帖子所属板块有审核权的管理成员),
|
||||
// 级联软删整棵子树
|
||||
func (s *CommentService) Delete(actor *Actor, commentID, userID uint) error {
|
||||
var comment model.Comment
|
||||
if err := s.db.First(&comment, commentID).Error; err != nil {
|
||||
return errors.New("评论不存在")
|
||||
return ErrCommentNotFound
|
||||
}
|
||||
// 权限校验:作者本人或板块审核权
|
||||
if comment.UserID != userID {
|
||||
var post model.Post
|
||||
if err := s.db.Select("id", "board_id").First(&post, comment.PostID).Error; err != nil {
|
||||
return ErrCommentNotFound
|
||||
}
|
||||
if !actor.CanModerateBoard(post.BoardID) {
|
||||
return ErrCommentForbidden
|
||||
}
|
||||
// 权限校验:作者本人或管理员
|
||||
if comment.UserID != userID && role != RoleAdmin {
|
||||
return errors.New("无权限删除此评论")
|
||||
}
|
||||
// 收集子树:取同楼层全部评论,多轮标记出以目标为祖先的集合(含自身,深度有限必然收敛)
|
||||
var all []model.Comment
|
||||
@@ -247,11 +270,27 @@ func (s *CommentService) Delete(commentID, userID uint, role string) error {
|
||||
for id := range descendants {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
// 软删子树并按实际条数递减帖子评论数
|
||||
// 只有已发布评论曾计入 comment_count,递减时排除待审/被拒评论。
|
||||
// all 含同楼层全部子评论(删除主评论时目标自身不在 all 内,需单独计入)
|
||||
publishedCnt := 0
|
||||
if comment.Status == model.ContentStatusPublished {
|
||||
publishedCnt++
|
||||
}
|
||||
for _, c := range all {
|
||||
if c.ID == comment.ID {
|
||||
continue
|
||||
}
|
||||
if descendants[c.ID] && c.Status == model.ContentStatusPublished {
|
||||
publishedCnt++
|
||||
}
|
||||
}
|
||||
// 软删子树并按已发布条数递减帖子评论数
|
||||
if err := s.db.Delete(&model.Comment{}, ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if publishedCnt > 0 {
|
||||
s.db.Model(&model.Post{}).Where("id = ?", comment.PostID).
|
||||
UpdateColumn("comment_count", gorm.Expr("GREATEST(comment_count - ?, 0)", len(ids)))
|
||||
UpdateColumn("comment_count", gorm.Expr("GREATEST(comment_count - ?, 0)", publishedCnt))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
277
backend/service/moderation.go
Normal file
277
backend/service/moderation.go
Normal file
@@ -0,0 +1,277 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 内容审核相关错误
|
||||
var (
|
||||
ErrModerationForbidden = errors.New("无权审核该板块的内容")
|
||||
ErrNotPending = errors.New("该内容不在待审核状态")
|
||||
)
|
||||
|
||||
// ModerationService 帖子/评论审核队列
|
||||
type ModerationService struct {
|
||||
db *gorm.DB
|
||||
notif *NotificationService
|
||||
}
|
||||
|
||||
func NewModerationService(db *gorm.DB, notif *NotificationService) *ModerationService {
|
||||
return &ModerationService{db: db, notif: notif}
|
||||
}
|
||||
|
||||
// PendingCommentItem 待审评论列表项(带上所属帖子与板块,便于按板块隔离与展示)
|
||||
type PendingCommentItem struct {
|
||||
ID uint `json:"id"`
|
||||
PostID uint `json:"post_id"`
|
||||
PostTitle string `json:"post_title"`
|
||||
BoardID uint `json:"board_id"`
|
||||
Board model.Board `json:"board"`
|
||||
Content string `json:"content"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
User model.User `json:"user"`
|
||||
}
|
||||
|
||||
// boardScope 板块管理员只能看到/操作被授权板块;管理员及以上不限
|
||||
func boardScope(q *gorm.DB, actor *Actor) *gorm.DB {
|
||||
if actor.Role == model.RoleBoardAdmin {
|
||||
return q.Where("board_id IN ?", actor.BoardIDs)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// PendingPosts 待审核帖子分页
|
||||
func (s *ModerationService) PendingPosts(actor *Actor, page, size int) ([]model.Post, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 50 {
|
||||
size = 15
|
||||
}
|
||||
q := s.db.Model(&model.Post{}).Where("status = ?", model.ContentStatusPending)
|
||||
q = boardScope(q, actor)
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var posts []model.Post
|
||||
if err := q.Order("created_at ASC").
|
||||
Offset((page - 1) * size).Limit(size).
|
||||
Preload("Board").Preload("User").
|
||||
Find(&posts).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return posts, total, nil
|
||||
}
|
||||
|
||||
// PendingComments 待审核评论分页(JOIN 帖子取板块与标题)
|
||||
func (s *ModerationService) PendingComments(actor *Actor, page, size int) ([]PendingCommentItem, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 50 {
|
||||
size = 15
|
||||
}
|
||||
base := s.db.Table("comments").
|
||||
Joins("JOIN posts ON posts.id = comments.post_id").
|
||||
Where("comments.status = ? AND comments.deleted_at IS NULL AND posts.deleted_at IS NULL",
|
||||
model.ContentStatusPending)
|
||||
if actor.Role == model.RoleBoardAdmin {
|
||||
base = base.Where("posts.board_id IN ?", actor.BoardIDs)
|
||||
}
|
||||
var total int64
|
||||
if err := base.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
type row struct {
|
||||
ID uint
|
||||
PostID uint
|
||||
PostTitle string
|
||||
BoardID uint
|
||||
Content string
|
||||
CreatedAt time.Time
|
||||
UserID uint
|
||||
}
|
||||
var rows []row
|
||||
if err := base.Select("comments.id, comments.post_id, posts.title AS post_title, posts.board_id, " +
|
||||
"comments.content, comments.created_at, comments.user_id").
|
||||
Order("comments.created_at ASC").
|
||||
Offset((page - 1) * size).Limit(size).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
items := make([]PendingCommentItem, 0, len(rows))
|
||||
if len(rows) > 0 {
|
||||
userIDs := map[uint]bool{}
|
||||
boardIDs := map[uint]bool{}
|
||||
for _, r := range rows {
|
||||
userIDs[r.UserID] = true
|
||||
if r.BoardID > 0 {
|
||||
boardIDs[r.BoardID] = true
|
||||
}
|
||||
}
|
||||
var users []model.User
|
||||
s.db.Where("id IN ?", keys(userIDs)).Find(&users)
|
||||
userMap := map[uint]model.User{}
|
||||
for _, u := range users {
|
||||
userMap[u.ID] = u
|
||||
}
|
||||
var boards []model.Board
|
||||
s.db.Where("id IN ?", keys(boardIDs)).Find(&boards)
|
||||
boardMap := map[uint]model.Board{}
|
||||
for _, b := range boards {
|
||||
boardMap[b.ID] = b
|
||||
}
|
||||
for _, r := range rows {
|
||||
items = append(items, PendingCommentItem{
|
||||
ID: r.ID,
|
||||
PostID: r.PostID,
|
||||
PostTitle: r.PostTitle,
|
||||
BoardID: r.BoardID,
|
||||
Board: boardMap[r.BoardID],
|
||||
Content: r.Content,
|
||||
CreatedAt: r.CreatedAt,
|
||||
User: userMap[r.UserID],
|
||||
})
|
||||
}
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// PendingCounts 当前操作者可见的待审数量(导航角标)
|
||||
func (s *ModerationService) PendingCounts(actor *Actor) (posts int64, comments int64) {
|
||||
q := s.db.Model(&model.Post{}).Where("status = ?", model.ContentStatusPending)
|
||||
boardScope(q, actor).Count(&posts)
|
||||
|
||||
cq := s.db.Table("comments").
|
||||
Joins("JOIN posts ON posts.id = comments.post_id").
|
||||
Where("comments.status = ? AND comments.deleted_at IS NULL AND posts.deleted_at IS NULL",
|
||||
model.ContentStatusPending)
|
||||
if actor.Role == model.RoleBoardAdmin {
|
||||
cq = cq.Where("posts.board_id IN ?", actor.BoardIDs)
|
||||
}
|
||||
cq.Count(&comments)
|
||||
return
|
||||
}
|
||||
|
||||
// ApprovePost 帖子审核通过
|
||||
func (s *ModerationService) ApprovePost(actor *Actor, id uint) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var post model.Post
|
||||
if err := tx.First(&post, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !actor.CanModerateBoard(post.BoardID) {
|
||||
return ErrModerationForbidden
|
||||
}
|
||||
if post.Status != model.ContentStatusPending {
|
||||
return ErrNotPending
|
||||
}
|
||||
if err := tx.Model(&post).Update("status", model.ContentStatusPublished).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
s.notif.Create(post.UserID, actor.ID, model.NotificationTypeApproved, post.ID, 0,
|
||||
"你的帖子《"+post.Title+"》已通过审核")
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RejectPost 帖子审核拒绝(标记 rejected,不物理删除;作者仍可在详情页看到结果)
|
||||
func (s *ModerationService) RejectPost(actor *Actor, id uint) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var post model.Post
|
||||
if err := tx.First(&post, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !actor.CanModerateBoard(post.BoardID) {
|
||||
return ErrModerationForbidden
|
||||
}
|
||||
if post.Status != model.ContentStatusPending {
|
||||
return ErrNotPending
|
||||
}
|
||||
if err := tx.Model(&post).Update("status", model.ContentStatusRejected).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
s.notif.Create(post.UserID, actor.ID, model.NotificationTypeRejected, post.ID, 0,
|
||||
"你的帖子《"+post.Title+"》未通过审核")
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ApproveComment 评论审核通过(通过时才计入帖子评论数)
|
||||
func (s *ModerationService) ApproveComment(actor *Actor, id uint) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var cm model.Comment
|
||||
if err := tx.First(&cm, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var post model.Post
|
||||
if err := tx.Select("id", "board_id", "title").First(&post, cm.PostID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !actor.CanModerateBoard(post.BoardID) {
|
||||
return ErrModerationForbidden
|
||||
}
|
||||
if cm.Status != model.ContentStatusPending {
|
||||
return ErrNotPending
|
||||
}
|
||||
if err := tx.Model(&cm).Update("status", model.ContentStatusPublished).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&model.Post{}).Where("id = ?", cm.PostID).
|
||||
UpdateColumn("comment_count", gorm.Expr("comment_count + 1")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
s.notif.Create(cm.UserID, actor.ID, model.NotificationTypeApproved, cm.PostID, cm.ID,
|
||||
"你在帖子《"+post.Title+"》下的评论已通过审核")
|
||||
// 评论此时才公开,补发送业务通知(以评论者为 actor):
|
||||
// 主评论通知帖子作者;子回复通知父评论作者
|
||||
if cm.ParentID == nil {
|
||||
s.notif.Create(post.UserID, cm.UserID, model.NotificationTypeComment, cm.PostID, cm.ID, cm.Content)
|
||||
} else {
|
||||
var parent model.Comment
|
||||
if err := tx.Select("user_id").First(&parent, *cm.ParentID).Error; err == nil {
|
||||
s.notif.Create(parent.UserID, cm.UserID, model.NotificationTypeReply, cm.PostID, cm.ID, cm.Content)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RejectComment 评论审核拒绝
|
||||
func (s *ModerationService) RejectComment(actor *Actor, id uint) error {
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var cm model.Comment
|
||||
if err := tx.First(&cm, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var post model.Post
|
||||
if err := tx.Select("id", "board_id", "title").First(&post, cm.PostID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !actor.CanModerateBoard(post.BoardID) {
|
||||
return ErrModerationForbidden
|
||||
}
|
||||
if cm.Status != model.ContentStatusPending {
|
||||
return ErrNotPending
|
||||
}
|
||||
if err := tx.Model(&cm).Update("status", model.ContentStatusRejected).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
s.notif.Create(cm.UserID, actor.ID, model.NotificationTypeRejected, cm.PostID, cm.ID,
|
||||
"你在帖子《"+post.Title+"》下的评论未通过审核")
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func keys(m map[uint]bool) []uint {
|
||||
out := make([]uint, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -9,6 +9,12 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 帖子操作错误
|
||||
var (
|
||||
ErrPostNotFound = errors.New("帖子不存在")
|
||||
ErrPostForbidden = errors.New("无权限操作此帖子")
|
||||
)
|
||||
|
||||
// PostService 帖子服务
|
||||
type PostService struct {
|
||||
db *gorm.DB
|
||||
@@ -263,19 +269,51 @@ func (s *PostService) ToggleRecommend(id uint) (bool, error) {
|
||||
return newVal, nil
|
||||
}
|
||||
|
||||
// GetByID 获取帖子详情
|
||||
func (s *PostService) GetByID(id uint) (*model.Post, error) {
|
||||
// visibleTo 非已发布帖子仅作者本人或对该板块有审核权的管理成员可见。
|
||||
// loadActor 为懒加载回调:仅访问非已发布帖且访问者非作者时才触发,避免常规浏览多查 DB
|
||||
func visibleToPost(post *model.Post, viewerID uint, loadActor func() *Actor) bool {
|
||||
if post.Status == model.ContentStatusPublished {
|
||||
return true
|
||||
}
|
||||
if viewerID > 0 && post.UserID == viewerID {
|
||||
return true
|
||||
}
|
||||
if loadActor == nil {
|
||||
return false
|
||||
}
|
||||
return loadActor().CanModerateBoard(post.BoardID)
|
||||
}
|
||||
|
||||
// GetByIDForViewer 获取帖子详情(带可见性校验);通过校验才计入浏览量。
|
||||
// viewerID 为当前登录用户(未登录传 0),loadActor 可传 nil
|
||||
func (s *PostService) GetByIDForViewer(id, viewerID uint, loadActor func() *Actor) (*model.Post, error) {
|
||||
var post model.Post
|
||||
if err := s.db.Preload("Board").Preload("User").First(&post, id).Error; err != nil {
|
||||
return nil, err
|
||||
return nil, ErrPostNotFound
|
||||
}
|
||||
// 增加浏览量
|
||||
if !visibleToPost(&post, viewerID, loadActor) {
|
||||
return nil, ErrPostNotFound
|
||||
}
|
||||
// 增加浏览量(待审/被拒内容不计)
|
||||
s.db.Model(&post).UpdateColumn("view_count", gorm.Expr("view_count + 1"))
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Create 创建帖子
|
||||
func (s *PostService) Create(userID uint, boardID uint, title, content, tags, postType string) (*model.Post, error) {
|
||||
// EnsurePostVisible 校验帖子对当前访问者可见(评论列表等场景复用,不增加浏览量)
|
||||
func (s *PostService) EnsurePostVisible(postID, viewerID uint, loadActor func() *Actor) error {
|
||||
var post model.Post
|
||||
if err := s.db.Select("id", "user_id", "board_id", "status").First(&post, postID).Error; err != nil {
|
||||
return ErrPostNotFound
|
||||
}
|
||||
if !visibleToPost(&post, viewerID, loadActor) {
|
||||
return ErrPostNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create 创建帖子。status 由 handler 按角色计算:
|
||||
// 管理团队成员直发 published,普通用户进入 pending 等待审核
|
||||
func (s *PostService) Create(userID uint, boardID uint, title, content, tags, postType, status string) (*model.Post, error) {
|
||||
title = strings.TrimSpace(title)
|
||||
content = strings.TrimSpace(content)
|
||||
if title == "" {
|
||||
@@ -287,6 +325,9 @@ func (s *PostService) Create(userID uint, boardID uint, title, content, tags, po
|
||||
if boardID == 0 {
|
||||
return nil, errors.New("请选择板块")
|
||||
}
|
||||
if status != model.ContentStatusPending && status != model.ContentStatusPublished {
|
||||
status = model.ContentStatusPending
|
||||
}
|
||||
|
||||
// 新用户 24h 冷静期校验
|
||||
if err := s.checkNewUserCooldown(userID); err != nil {
|
||||
@@ -300,7 +341,7 @@ func (s *PostService) Create(userID uint, boardID uint, title, content, tags, po
|
||||
Content: content,
|
||||
Tags: tags,
|
||||
PostType: postType,
|
||||
Status: model.ContentStatusPublished,
|
||||
Status: status,
|
||||
}
|
||||
if err := s.db.Create(post).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -323,15 +364,15 @@ func (s *PostService) checkNewUserCooldown(userID uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update 更新帖子(仅作者或管理员可操作)
|
||||
func (s *PostService) Update(postID, userID uint, role string, title, content, tags string) (*model.Post, error) {
|
||||
// Update 更新帖子(作者本人,或对该板块有审核权的管理成员)
|
||||
func (s *PostService) Update(actor *Actor, postID, userID uint, title, content, tags string) (*model.Post, error) {
|
||||
var post model.Post
|
||||
if err := s.db.First(&post, postID).Error; err != nil {
|
||||
return nil, errors.New("帖子不存在")
|
||||
return nil, ErrPostNotFound
|
||||
}
|
||||
// 权限校验:作者本人或管理员
|
||||
if post.UserID != userID && role != RoleAdmin {
|
||||
return nil, errors.New("无权限编辑此帖子")
|
||||
// 权限校验:作者本人或板块审核权
|
||||
if post.UserID != userID && !actor.CanModerateBoard(post.BoardID) {
|
||||
return nil, ErrPostForbidden
|
||||
}
|
||||
|
||||
updates := map[string]interface{}{}
|
||||
@@ -358,15 +399,15 @@ func (s *PostService) Update(postID, userID uint, role string, title, content, t
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Delete 删除帖子(仅作者或管理员可操作)
|
||||
func (s *PostService) Delete(postID, userID uint, role string) error {
|
||||
// Delete 删除帖子(作者本人,或对该板块有审核权的管理成员)
|
||||
func (s *PostService) Delete(actor *Actor, postID, userID uint) error {
|
||||
var post model.Post
|
||||
if err := s.db.First(&post, postID).Error; err != nil {
|
||||
return errors.New("帖子不存在")
|
||||
return ErrPostNotFound
|
||||
}
|
||||
// 权限校验:作者本人或管理员
|
||||
if post.UserID != userID && role != RoleAdmin {
|
||||
return errors.New("无权限删除此帖子")
|
||||
// 权限校验:作者本人或板块审核权
|
||||
if post.UserID != userID && !actor.CanModerateBoard(post.BoardID) {
|
||||
return ErrPostForbidden
|
||||
}
|
||||
// 软删除(gorm DeletedAt)
|
||||
if err := s.db.Delete(&post).Error; err != nil {
|
||||
|
||||
@@ -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,17 +206,20 @@ 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">
|
||||
{canModerateAny(me.user) && (
|
||||
<QuickLink
|
||||
href="/admin/users"
|
||||
icon={<Users size={18} />}
|
||||
title="用户管理"
|
||||
desc="查看全站成员,授予管理员权限或封禁违规账号"
|
||||
soft="var(--accent-soft)"
|
||||
color="var(--accent)"
|
||||
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} />}
|
||||
@@ -223,6 +228,18 @@ export default async function AdminDashboardPage() {
|
||||
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} />}
|
||||
@@ -231,6 +248,7 @@ export default async function AdminDashboardPage() {
|
||||
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,16 +101,21 @@ 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)" }}>
|
||||
{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()}
|
||||
@@ -102,6 +130,8 @@ export default function NotificationsClient({ initialData }: { initialData: Noti
|
||||
? "回复了你的评论"
|
||||
: "点赞了你的帖子"}
|
||||
</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,8 +514,11 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 非公开帖不开放评论(后端同样拒绝),给出状态提示 */}
|
||||
{isPublished ? (
|
||||
<CommentSection
|
||||
postId={id}
|
||||
boardId={post.board_id}
|
||||
comments={comments}
|
||||
total={commentsData.total}
|
||||
totalComments={commentsData.total_comments}
|
||||
@@ -505,6 +526,20 @@ export default async function PostDetailPage({ params, searchParams }: PageProps
|
||||
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("");
|
||||
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("");
|
||||
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)" }}>
|
||||
{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