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 {
|
||||
Role string `json:"role"`
|
||||
// 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": "操作失败"})
|
||||
|
||||
@@ -17,10 +17,11 @@ var (
|
||||
)
|
||||
|
||||
// setAuthCookies 设置认证 cookie:
|
||||
// - access token(HttpOnly,15min)
|
||||
// - refresh token(HttpOnly,7天,Path=/,供 Next middleware 在页面/RSC
|
||||
// 请求中读取并静默轮转;仅 /api/auth/refresh 端点消费)
|
||||
// - CSRF token(JS 可读,7天,双提交校验)
|
||||
// - access token(HttpOnly,15min)
|
||||
// - 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()})
|
||||
@@ -26,7 +40,7 @@ func (h *Handlers) PostComments(c *gin.Context) {
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"comments": comments,
|
||||
"total": floors, // 楼层数(主评论数)→ 前端分页与楼层号计算
|
||||
"total": floors, // 楼层数(主评论数)→ 前端分页与楼层号计算
|
||||
"total_comments": totalComments, // 全部评论数(含回复)→ 展示徽标
|
||||
"page": page,
|
||||
"size": size,
|
||||
@@ -52,19 +66,26 @@ 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 parent == nil {
|
||||
// 主评论:通知帖子作者(排除自己评论自己的帖子)
|
||||
if authorID, e := h.Post.GetAuthorID(uint(id)); e == nil {
|
||||
h.Notification.Create(authorID, claims.ID, model.NotificationTypeComment, uint(id), comment.ID, req.Content)
|
||||
if comment.Status == model.ContentStatusPublished {
|
||||
if parent == nil {
|
||||
// 主评论:通知帖子作者(排除自己评论自己的帖子)
|
||||
if authorID, e := h.Post.GetAuthorID(uint(id)); e == nil {
|
||||
h.Notification.Create(authorID, claims.ID, model.NotificationTypeComment, uint(id), comment.ID, req.Content)
|
||||
}
|
||||
} else {
|
||||
// 子回复:通知父评论作者(Notification.Create 内部排除自我通知)
|
||||
h.Notification.Create(parent.UserID, claims.ID, model.NotificationTypeReply, uint(id), comment.ID, req.Content)
|
||||
}
|
||||
} else {
|
||||
// 子回复:通知父评论作者(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 {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
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"
|
||||
@@ -39,7 +72,7 @@ type User struct {
|
||||
Role Role `gorm:"size:16;default:user" json:"role"`
|
||||
Banned bool `gorm:"default:false" json:"banned"`
|
||||
TokenVersion int `gorm:"default:0" json:"-"` // token 版本号,改密码/封禁时递增使旧 JWT 失效
|
||||
LastSeenAt *time.Time `gorm:"index" json:"-"` // 最近活跃时间(在线统计,限频更新)
|
||||
LastSeenAt *time.Time `gorm:"index" json:"-"` // 最近活跃时间(在线统计,限频更新)
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
@@ -136,15 +169,17 @@ type Checkin struct {
|
||||
|
||||
// 通知类型
|
||||
const (
|
||||
NotificationTypeComment = "comment" // 评论了你的帖子
|
||||
NotificationTypeReply = "reply" // 回复了你的评论
|
||||
NotificationTypeLike = "like" // 点赞了你的帖子
|
||||
NotificationTypeComment = "comment" // 评论了你的帖子
|
||||
NotificationTypeReply = "reply" // 回复了你的评论
|
||||
NotificationTypeLike = "like" // 点赞了你的帖子
|
||||
NotificationTypeApproved = "approved" // 内容审核通过
|
||||
NotificationTypeRejected = "rejected" // 内容审核未通过
|
||||
)
|
||||
|
||||
// Notification 站内通知
|
||||
type Notification struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"index;not null" json:"user_id"` // 接收通知的用户
|
||||
UserID uint `gorm:"index;not null" json:"user_id"` // 接收通知的用户
|
||||
ActorID uint `gorm:"not null" json:"actor_id"` // 触发通知的用户
|
||||
Type string `gorm:"size:16;not null;index" json:"type"` // comment | like
|
||||
PostID uint `gorm:"index;not null" json:"post_id"` // 关联帖子
|
||||
@@ -164,7 +199,7 @@ type Announcement struct {
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
Tag string `gorm:"size:32;not null;default:公告" json:"tag"`
|
||||
TagColor string `gorm:"size:16;not null;default:blue" json:"tag_color"` // blue/green/orange/red/purple/gray
|
||||
Published bool `gorm:"not null;index" json:"published"` // 显式写入 false;不可用 default:true,否则草稿零值会被 GORM 省略而落成已发布
|
||||
Published bool `gorm:"not null;index" json:"published"` // 显式写入 false;不可用 default:true,否则草稿零值会被 GORM 省略而落成已发布
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -20,9 +20,9 @@ var ErrAlreadyCheckedIn = errors.New("今日已签到")
|
||||
// CheckinStatus 签到状态(首页右栏与签到接口共用)
|
||||
type CheckinStatus struct {
|
||||
CheckedToday bool `json:"checked_today"`
|
||||
Streak int `json:"streak"` // 连续签到天数
|
||||
TotalPoints int `json:"total_points"` // 累计积分(签到所得)
|
||||
TodayPoints int `json:"today_points"` // 今日签到可得积分
|
||||
Streak int `json:"streak"` // 连续签到天数
|
||||
TotalPoints int `json:"total_points"` // 累计积分(签到所得)
|
||||
TodayPoints int `json:"today_points"` // 今日签到可得积分
|
||||
}
|
||||
|
||||
// CheckinService 每日签到
|
||||
|
||||
@@ -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
|
||||
}
|
||||
// 更新帖子评论数
|
||||
s.db.Model(&post).UpdateColumn("comment_count", gorm.Expr("comment_count + 1"))
|
||||
// 仅已发布评论立即计入评论数;待审评论通过审核时才 +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 && role != RoleAdmin {
|
||||
return errors.New("无权限删除此评论")
|
||||
// 权限校验:作者本人或板块审核权
|
||||
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
|
||||
}
|
||||
}
|
||||
// 收集子树:取同楼层全部评论,多轮标记出以目标为祖先的集合(含自身,深度有限必然收敛)
|
||||
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
|
||||
}
|
||||
s.db.Model(&model.Post{}).Where("id = ?", comment.PostID).
|
||||
UpdateColumn("comment_count", gorm.Expr("GREATEST(comment_count - ?, 0)", len(ids)))
|
||||
if publishedCnt > 0 {
|
||||
s.db.Model(&model.Post{}).Where("id = ?", comment.PostID).
|
||||
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
|
||||
}
|
||||
@@ -25,7 +25,7 @@ type OverviewStats struct {
|
||||
TodayPosts int64 `json:"today_posts"`
|
||||
TodayUsers int64 `json:"today_users"`
|
||||
TodayComments int64 `json:"today_comments"`
|
||||
Online int64 `json:"online"` // 近 5 分钟活跃用户
|
||||
Online int64 `json:"online"` // 近 5 分钟活跃用户
|
||||
PeakOnline int64 `json:"peak_online"` // 历史在线峰值
|
||||
}
|
||||
|
||||
@@ -65,13 +65,13 @@ type NewUserItem struct {
|
||||
|
||||
// OverviewData 首页聚合数据
|
||||
type OverviewData struct {
|
||||
Stats OverviewStats `json:"stats"`
|
||||
Hot []PostListItem `json:"hot"`
|
||||
ActiveUsers []ActiveUser `json:"active_users"`
|
||||
Boards []BoardCount `json:"boards"`
|
||||
Announcements []AnnouncementItem `json:"announcements"`
|
||||
NewUsers []NewUserItem `json:"new_users"`
|
||||
Checkin *CheckinStatus `json:"checkin,omitempty"`
|
||||
Stats OverviewStats `json:"stats"`
|
||||
Hot []PostListItem `json:"hot"`
|
||||
ActiveUsers []ActiveUser `json:"active_users"`
|
||||
Boards []BoardCount `json:"boards"`
|
||||
Announcements []AnnouncementItem `json:"announcements"`
|
||||
NewUsers []NewUserItem `json:"new_users"`
|
||||
Checkin *CheckinStatus `json:"checkin,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
|
||||
@@ -9,6 +9,12 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 帖子操作错误
|
||||
var (
|
||||
ErrPostNotFound = errors.New("帖子不存在")
|
||||
ErrPostForbidden = errors.New("无权限操作此帖子")
|
||||
)
|
||||
|
||||
// PostService 帖子服务
|
||||
type PostService struct {
|
||||
db *gorm.DB
|
||||
@@ -67,14 +73,14 @@ type PostListItem struct {
|
||||
PostType string `json:"post_type"`
|
||||
Pinned int `json:"pinned"`
|
||||
Recommended bool `json:"recommended"`
|
||||
LikeCount int `json:"like_count"`
|
||||
ViewCount int `json:"view_count"`
|
||||
CommentCount int `json:"comment_count"`
|
||||
Liked bool `json:"liked"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LikeCount int `json:"like_count"`
|
||||
ViewCount int `json:"view_count"`
|
||||
CommentCount int `json:"comment_count"`
|
||||
Liked bool `json:"liked"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastReply *LastReplyInfo `json:"last_reply,omitempty"`
|
||||
Board model.Board `json:"board"`
|
||||
User model.User `json:"user"`
|
||||
Board model.Board `json:"board"`
|
||||
User model.User `json:"user"`
|
||||
}
|
||||
|
||||
// fillLastReply 批量填充每帖最后一条已发布评论(发帖人+时间),
|
||||
@@ -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 {
|
||||
|
||||
@@ -71,9 +71,9 @@ const (
|
||||
// DefaultRateLimiter 创建默认速率限制器
|
||||
func DefaultRateLimiter() *RateLimiter {
|
||||
rl := NewRateLimiter()
|
||||
rl.SetLimit(RateLogin, 20) // 登录 20/分钟
|
||||
rl.SetLimit(RateRegister, 10) // 注册 10/分钟
|
||||
rl.SetLimit(RatePost, 10) // 发帖 10/分钟
|
||||
rl.SetLimit(RateComment, 30) // 评论 30/分钟
|
||||
rl.SetLimit(RateLogin, 20) // 登录 20/分钟
|
||||
rl.SetLimit(RateRegister, 10) // 注册 10/分钟
|
||||
rl.SetLimit(RatePost, 10) // 发帖 10/分钟
|
||||
rl.SetLimit(RateComment, 30) // 评论 30/分钟
|
||||
return rl
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user