This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/internal/service/post_service.go
Victor_Jay 22a302315a feat: wangEditor 替换为 ByteMD Markdown 编辑器
- 移除 wangEditor 5 库文件(1.27MB JS + 14KB CSS,含手动 hack)
- 集成 ByteMD 1.22.0(基于 CodeMirror 5,不依赖 contentEditable)
- 编辑器输出 Markdown 原文,后端 goldmark + bluemonday 双重防护渲染 HTML
- 删除 editor.js 中 scrollIntoView hack、code-lang-label DOM 注入、PreviewAPI 调用
- 清理 posts.css 中 ~200 行 wangEditor 样式覆盖(w-e-* 类名)
- 清理 show.html 中 code-lang-label JS 注入(goldmark 自带 language-xxx class)
- 更新 CSP 安全策略:移除 CodeMirror 注释,保留 esm.sh CDN
- go.mod:bluemonday 和 goldmark 均保留为直接依赖(纵深防御)
2026-05-28 02:16:50 +08:00

223 lines
6.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package service
import (
"bytes"
"fmt"
"metazone.cc/metalab/internal/common"
"metazone.cc/metalab/internal/config"
"metazone.cc/metalab/internal/model"
"github.com/microcosm-cc/bluemonday"
"github.com/yuin/goldmark"
)
// sanitizePolicy 纵深防御:对 goldmark 输出的 HTML 再做一层消毒
// goldmark 默认已过滤原始 HTML 和危险链接,但 bluemonday 作为第二道防线
// UGC 策略会剥离 code/pre 的 class 属性,需要显式放行以保留 language-xxx
var sanitizePolicy = func() *bluemonday.Policy {
p := bluemonday.UGCPolicy()
p.AllowAttrs("class").OnElements("code", "pre")
return p
}()
// postStore 帖子服务所需的最小仓储接口ISP
type postStore interface {
Create(post *model.Post) error
FindByID(id uint) (*model.Post, error)
FindByIDWithAuthor(id uint) (*model.Post, error)
FindPageable(keyword string, offset, limit int) ([]model.Post, int64, error)
FindAdminPageable(keyword, status string, offset, limit int) ([]model.Post, int64, error)
Update(post *model.Post) error
SoftDelete(id uint) error
Restore(id uint) error
}
// PostService 帖子业务逻辑
type PostService struct {
repo postStore
ss *config.SiteSettings
md goldmark.Markdown
}
// NewPostService 构造函数
func NewPostService(repo postStore, ss *config.SiteSettings) *PostService {
return &PostService{
repo: repo,
ss: ss,
md: goldmark.New(),
}
}
// auditEnabled 审核是否开启
func (s *PostService) auditEnabled() bool {
return s.ss.IsAuditEnabled()
}
// renderMarkdown 将 Markdown 文本渲染为安全 HTML
// goldmark默认安全模式→ bluemonday纵深防御
func (s *PostService) renderMarkdown(body string) (string, error) {
var buf bytes.Buffer
if err := s.md.Convert([]byte(body), &buf); err != nil {
return "", fmt.Errorf("markdown render: %w", err)
}
return sanitizePolicy.Sanitize(buf.String()), nil
}
// RenderMarkdown 对外暴露,用于预览 API
func (s *PostService) RenderMarkdown(body string) (string, error) {
return s.renderMarkdown(body)
}
// Create 创建帖子
func (s *PostService) Create(userID uint, title, body string) (*model.Post, error) {
bodyHTML, err := s.renderMarkdown(body)
if err != nil {
return nil, err
}
status := model.PostStatusApproved
if s.auditEnabled() {
status = model.PostStatusDraft
}
post := &model.Post{
Title: title,
Body: body,
BodyHTML: bodyHTML,
UserID: userID,
Status: status,
AllowComment: true,
}
if err := s.repo.Create(post); err != nil {
return nil, err
}
return post, nil
}
// GetByID 按 ID 获取帖子(含作者名,仅 approved 公开可见)
func (s *PostService) GetByID(id uint) (*model.Post, error) {
post, err := s.repo.FindByIDWithAuthor(id)
if err != nil {
return nil, common.ErrUserNotFound // 复用哨兵表示资源不存在
}
return post, nil
}
// List 公开帖子列表(仅 approved
func (s *PostService) List(keyword string, page, pageSize int) ([]model.Post, int64, error) {
p := common.Pagination{Page: page, PageSize: pageSize}
p.DefaultPagination()
return s.repo.FindPageable(keyword, p.Offset(), p.PageSize)
}
// ListAdmin 管理后台帖子列表(全状态)
func (s *PostService) ListAdmin(keyword, status string, page, pageSize int) ([]model.Post, int64, error) {
p := common.Pagination{Page: page, PageSize: pageSize}
p.DefaultPagination()
return s.repo.FindAdminPageable(keyword, status, p.Offset(), p.PageSize)
}
// Update 编辑帖子(权限在 controller 层检查)
func (s *PostService) Update(postID uint, title, body string) error {
post, err := s.repo.FindByID(postID)
if err != nil {
return common.ErrUserNotFound
}
if post.Status == model.PostStatusPending || post.Status == model.PostStatusLocked {
return fmt.Errorf("当前状态不允许编辑")
}
bodyHTML, err := s.renderMarkdown(body)
if err != nil {
return err
}
post.Title = title
post.Body = body
post.BodyHTML = bodyHTML
// rejected 状态编辑后自动重置为 draft
if post.Status == model.PostStatusRejected {
post.Status = model.PostStatusDraft
post.RejectReason = ""
}
return s.repo.Update(post)
}
// Delete 软删除(权限在 controller 层检查)
func (s *PostService) Delete(postID uint) error {
return s.repo.SoftDelete(postID)
}
// SubmitForAudit 提交审核draft → pending
func (s *PostService) SubmitForAudit(postID uint) error {
post, err := s.repo.FindByID(postID)
if err != nil {
return common.ErrUserNotFound
}
if post.Status != model.PostStatusDraft && post.Status != model.PostStatusRejected {
return fmt.Errorf("仅草稿和已退回帖子可提交审核")
}
post.Status = model.PostStatusPending
return s.repo.Update(post)
}
// Approve 审核通过pending → approved
func (s *PostService) Approve(postID uint) error {
post, err := s.repo.FindByID(postID)
if err != nil {
return common.ErrUserNotFound
}
if post.Status != model.PostStatusPending {
return fmt.Errorf("仅待审核帖子可通过")
}
post.Status = model.PostStatusApproved
post.RejectReason = ""
return s.repo.Update(post)
}
// Reject 退回pending/approved → rejected
func (s *PostService) Reject(postID uint, reason string) error {
post, err := s.repo.FindByID(postID)
if err != nil {
return common.ErrUserNotFound
}
if post.Status != model.PostStatusPending && post.Status != model.PostStatusApproved {
return fmt.Errorf("仅待审核和已发布帖子可退回")
}
post.Status = model.PostStatusRejected
post.RejectReason = reason
return s.repo.Update(post)
}
// Lock 锁定:任意状态 → locked
func (s *PostService) Lock(postID uint) error {
post, err := s.repo.FindByID(postID)
if err != nil {
return common.ErrUserNotFound
}
post.Status = model.PostStatusLocked
return s.repo.Update(post)
}
// Unlock 解锁locked → 草稿
func (s *PostService) Unlock(postID uint) error {
post, err := s.repo.FindByID(postID)
if err != nil {
return common.ErrUserNotFound
}
if post.Status != model.PostStatusLocked {
return fmt.Errorf("仅锁定状态可解锁")
}
post.Status = model.PostStatusDraft
return s.repo.Update(post)
}
// Restore 恢复软删除
func (s *PostService) Restore(postID uint) error {
return s.repo.Restore(postID)
}