Simplify admin publishing pipeline

This commit is contained in:
yarnom 2026-06-03 18:18:50 +08:00
parent 13e7e4026d
commit 9186801c7f
37 changed files with 750 additions and 3367 deletions

View file

@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
@ -19,11 +20,11 @@ type Server struct {
db *pgxpool.Pool
store *Store
builder *Builder
uploader *AssetUploader
deepSeek DeepSeekConfig
localLLM LocalLLMConfig
slugProvider string
adminDir string
staticDir string
ctx context.Context
}
@ -38,26 +39,22 @@ func NewServerWithConfig(db *pgxpool.Pool, cfg Config) *Server {
func NewServerWithContext(ctx context.Context, db *pgxpool.Pool, cfg Config) *Server {
var store *Store
var builder *Builder
var uploader *AssetUploader
if db != nil {
store = NewStore(db)
if cfg.PostsDir != "" && cfg.SiteDir != "" {
builder = NewBuilder(store, NewExporter(cfg.PostsDir), cfg.SiteDir)
builder.Start(ctx)
}
if cfg.AssetsDir != "" {
uploader = NewAssetUploader(store, cfg.AssetsDir)
}
}
return &Server{
db: db,
store: store,
builder: builder,
uploader: uploader,
deepSeek: cfg.DeepSeek,
localLLM: cfg.LocalLLM,
slugProvider: cfg.SlugProvider,
adminDir: cfg.AdminDir,
staticDir: cfg.StaticDir,
ctx: ctx,
}
}
@ -67,6 +64,7 @@ func (s *Server) Router() http.Handler {
r := gin.New()
r.Use(gin.Recovery())
r.Use(requestLogger())
r.GET("/healthz", s.health)
r.GET("/readyz", s.ready)
@ -82,8 +80,8 @@ func (s *Server) Router() http.Handler {
protected.Use(s.requireAuth)
protected.GET("/me", s.me)
protected.POST("/logout", s.logout)
protected.POST("/assets", s.uploadAsset)
protected.POST("/slug", s.generateSlug)
protected.GET("/audit-logs", s.listAuditLogs)
protected.GET("/posts", s.listPosts)
protected.POST("/posts", s.createPost)
protected.GET("/posts/:id", s.getPost)
@ -93,6 +91,8 @@ func (s *Server) Router() http.Handler {
protected.POST("/posts/:id/publish", s.publishPost)
protected.GET("/build-jobs/:id", s.getBuildJob)
r.NoRoute(s.siteFile)
return r
}
@ -119,6 +119,17 @@ func (s *Server) adminFile(c *gin.Context) {
s.adminPage(c)
}
func (s *Server) siteFile(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/api/") {
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
return
}
if serveSiteFile(c, s.staticDir) {
return
}
c.String(http.StatusNotFound, "not found")
}
func (s *Server) ready(c *gin.Context) {
if s.db == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{
@ -190,10 +201,12 @@ func (s *Server) login(c *gin.Context) {
result, err := s.store.Login(c.Request.Context(), input)
if err != nil {
s.audit(c, nil, "login_failed", "user", "", gin.H{"username": input.Username, "error": err.Error()})
writeStoreError(c, err)
return
}
SetSessionCookie(c, result.Token, result.ExpiresAt)
s.audit(c, &result.User, "login", "user", result.User.ID, gin.H{"username": result.User.Username})
c.JSON(http.StatusOK, gin.H{
"user": result.User,
"expiresAt": result.ExpiresAt,
@ -214,12 +227,14 @@ func (s *Server) logout(c *gin.Context) {
return
}
user, _ := currentUser(c)
token, _ := c.Cookie(SessionCookieName)
if err := s.store.Logout(c.Request.Context(), token); err != nil {
writeStoreError(c, err)
return
}
ClearSessionCookie(c)
s.audit(c, &user, "logout", "user", user.ID, gin.H{"username": user.Username})
c.JSON(http.StatusOK, gin.H{"ok": true})
}
@ -252,6 +267,7 @@ func (s *Server) createPost(c *gin.Context) {
writeStoreError(c, err)
return
}
s.auditCurrentUser(c, "post_create", "post", post.ID, postAuditDetails(post))
c.JSON(http.StatusCreated, gin.H{"post": post})
}
@ -271,6 +287,7 @@ func (s *Server) updatePost(c *gin.Context) {
writeStoreError(c, err)
return
}
s.auditCurrentUser(c, "post_update", "post", post.ID, postAuditDetails(post))
c.JSON(http.StatusOK, gin.H{"post": post})
}
@ -285,33 +302,14 @@ func (s *Server) deletePost(c *gin.Context) {
return
}
s.enqueueBuildJob(job)
details := gin.H{}
if job != nil {
details["buildJobId"] = job.ID
}
s.auditCurrentUser(c, "post_delete", "post", c.Param("id"), details)
c.JSON(http.StatusOK, gin.H{"ok": true, "buildJob": job})
}
func (s *Server) uploadAsset(c *gin.Context) {
if !s.requireStore(c) {
return
}
if s.uploader == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "asset uploader is not configured"})
return
}
file, header, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
defer file.Close()
asset, err := s.uploader.Upload(c.Request.Context(), file, header)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"asset": asset})
}
type GenerateSlugInput struct {
Title string `json:"title"`
Summary string `json:"summary"`
@ -345,9 +343,35 @@ func (s *Server) generateSlug(c *gin.Context) {
writeStoreError(c, err)
return
}
s.auditCurrentUser(c, "slug_generate", "post", input.PostID, gin.H{"title": input.Title, "slug": slug})
c.JSON(http.StatusOK, gin.H{"slug": slug})
}
func (s *Server) listAuditLogs(c *gin.Context) {
if !s.requireStore(c) {
return
}
opts := AuditLogListOptions{
Action: c.Query("action"),
ResourceType: c.Query("resourceType"),
Query: c.Query("query"),
Limit: queryInt(c, "limit"),
Offset: queryInt(c, "offset"),
}
logs, err := s.store.ListAuditLogs(c.Request.Context(), opts)
if err != nil {
writeStoreError(c, err)
return
}
total, err := s.store.CountAuditLogs(c.Request.Context(), opts)
if err != nil {
writeStoreError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"logs": logs, "total": total})
}
func (s *Server) generateSlugBase(ctx context.Context, title string, summary string) (string, error) {
switch strings.ToLower(strings.TrimSpace(s.slugProvider)) {
case "", "deepseek":
@ -385,6 +409,7 @@ func (s *Server) buildPost(c *gin.Context) {
}
s.enqueueBuildJob(&job)
s.auditCurrentUser(c, "build_create", "build_job", job.ID, gin.H{"postId": c.Param("id")})
c.JSON(http.StatusAccepted, gin.H{"buildJob": job})
}
@ -400,6 +425,12 @@ func (s *Server) publishPost(c *gin.Context) {
}
s.enqueueBuildJob(&job)
s.auditCurrentUser(c, "post_publish", "post", post.ID, gin.H{
"title": post.Title,
"slug": post.Slug,
"status": post.Status,
"buildJobId": job.ID,
})
c.JSON(http.StatusAccepted, gin.H{
"post": post,
@ -472,3 +503,58 @@ func writeStoreError(c *gin.Context, err error) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
func currentUser(c *gin.Context) (User, bool) {
user, ok := c.Request.Context().Value(userContextKey).(User)
return user, ok
}
func (s *Server) auditCurrentUser(c *gin.Context, action string, resourceType string, resourceID string, details map[string]any) {
user, ok := currentUser(c)
if !ok {
s.audit(c, nil, action, resourceType, resourceID, details)
return
}
s.audit(c, &user, action, resourceType, resourceID, details)
}
func (s *Server) audit(c *gin.Context, user *User, action string, resourceType string, resourceID string, details map[string]any) {
if s.store == nil {
return
}
var actorID *string
actorUsername := ""
if user != nil {
actorID = &user.ID
actorUsername = user.Username
}
if err := s.store.CreateAuditLog(c.Request.Context(), AuditLogInput{
ActorID: actorID,
ActorUsername: actorUsername,
Action: action,
ResourceType: resourceType,
ResourceID: resourceID,
IPAddress: c.ClientIP(),
UserAgent: c.Request.UserAgent(),
Details: details,
}); err != nil {
log.Printf("audit log failed: %v", err)
}
}
func requestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
started := time.Now()
c.Next()
log.Printf("%s %s %d %s %s", c.Request.Method, c.Request.URL.Path, c.Writer.Status(), time.Since(started), c.ClientIP())
}
}
func postAuditDetails(post Post) map[string]any {
return map[string]any{
"title": post.Title,
"slug": post.Slug,
"status": post.Status,
"version": post.Version,
}
}