feat(journal): add category show/update API routes and MCP tools

This commit is contained in:
Jakub Zych
2026-11-28 15:05:45 +01:00
parent a047d4284f
commit daa29c8aa8
8 changed files with 580 additions and 58 deletions

View File

@@ -18,6 +18,7 @@ const (
errPublishPermission = "You do not have permission to publish posts"
errEditPermission = "You do not have permission to edit this post"
errPostNotFound = "Post not found"
errCategoryNotFound = "Category not found"
errImageNotFound = "Image not found"
errValidationFailed = "Validation failed"
msgPostDeleted = "Post deleted"
@@ -26,6 +27,7 @@ const (
permAccessPosts = "golem15.journal.access_posts"
permAccessOtherPosts = "golem15.journal.access_other_posts"
permAccessPublish = "golem15.journal.access_publish"
permAccessCategories = "golem15.journal.access_categories"
journalCover = "golem15.journal.*"
)
@@ -105,6 +107,14 @@ func requireAccessPosts(w http.ResponseWriter, pr *bouncer.Principal) bool {
return true
}
func requireAccessCategories(w http.ResponseWriter, pr *bouncer.Principal) bool {
if !cabana.Allows(pr, []string{permAccessCategories}) {
writeAPIError(w, http.StatusForbidden, errInsufficientPerms)
return false
}
return true
}
func gdb(app *backpack.App) (*gorm.DB, error) {
if app == nil {
return nil, errors.New("journal api: application is not configured")

View File

@@ -0,0 +1,401 @@
package api
import (
"context"
"net/http"
"strconv"
"strings"
"unicode/utf8"
"git.golem15.com/golem15/sm-journal-plugin/classes"
"git.golem15.com/golem15/sm-journal-plugin/models"
translate "git.golem15.com/golem15/sm-translate-plugin/classes"
translatemodels "git.golem15.com/golem15/sm-translate-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/towel"
"git.golem15.com/golem15/summercms/modules/wire"
"gorm.io/gorm"
)
// ShowCategory is GET /_journal/api/v1/categories/{slug}. Resolves by default
// slug, then translated slug in the request locale, then numeric id.
func ShowCategory(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
db, err := gdb(app)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
dbCtx := db.WithContext(r.Context())
slug := strings.TrimSpace(r.PathValue("slug"))
cat, err := findCategoryBySlugOrID(dbCtx, slug, requestLocale(r))
if err != nil || cat == nil {
writeAPIError(w, http.StatusNotFound, errCategoryNotFound)
return
}
h1ToH2 := classes.EffectiveH1ToH2(r.Context(), dbCtx, appConfig(app))
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": serializeCategoryDetail(dbCtx, cat, h1ToH2)})
}
}
// UpdateCategory is PUT /_journal/api/v1/categories/{id}. Requires a backend
// principal with golem15.journal.access_categories. Only submitted fields
// change: name, slug, description, content (sanitized through the app's
// EmbedRegistry, with H1→H2 conversion while the H1 setting is on, blank
// stored as NULL), and optional translations.
func UpdateCategory(app *backpack.App) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r, pr, ok := requireBackendPrincipal(app, w, r)
if !ok {
return
}
if !requireAccessCategories(w, pr) {
return
}
db, err := gdb(app)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
dbCtx := db.WithContext(r.Context())
cat, err := findCategoryByID(dbCtx, r.PathValue("id"))
if err != nil || cat == nil {
writeAPIError(w, http.StatusNotFound, errCategoryNotFound)
return
}
body, err := readJSONObject(r)
if err != nil {
writeAPIError(w, http.StatusBadRequest, errValidationFailed)
return
}
before := snapshotCategory(cat)
verrs := applyCategoryUpdate(dbCtx, app, cat, body)
if verrs != nil {
writeValidation(w, verrs)
return
}
h1Count := 0
err = lagoon.Transaction(r.Context(), db, func(ctx context.Context, tx *gorm.DB) error {
if _, has := body["content"]; has && cat.Content != nil {
if classes.EffectiveH1ToH2(ctx, tx, appConfig(app)) {
converted, n := classes.ConvertH1(*cat.Content)
if n > 0 {
cat.Content = &converted
h1Count = n
}
}
}
if err := tx.Save(cat).Error; err != nil {
return err
}
if raw, has := body["translations"]; has {
if err := syncCategoryTranslations(ctx, tx, cat, raw); err != nil {
return err
}
}
cabana.EmitRecordSaved(ctx, app, tx, categorySavedEvent(ctx, before, cat))
return nil
})
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "Internal server error")
return
}
cooler.PurgeSiteCacheAfterCommit(r.Context(), nil, cooler.SiteCacheFromApp(app), "category", cat.Slug)
h1ToH2 := classes.EffectiveH1ToH2(r.Context(), dbCtx, appConfig(app))
payload := map[string]any{"data": serializeCategoryDetail(dbCtx, cat, h1ToH2)}
if h1Count > 0 {
msg := classes.EditorH1ConvertedCategory
if app != nil {
if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil {
msg = tr.Choice(r.Context(), classes.EditorH1ConvertedCategory, h1Count, nil)
}
}
payload["notices"] = []map[string]any{{"message": msg, "count": h1Count}}
}
wire.WriteJSON(w, http.StatusOK, payload)
}
}
func findCategoryBySlugOrID(db *gorm.DB, slug, locale string) (*models.Category, error) {
if slug == "" {
return nil, gorm.ErrRecordNotFound
}
var cat models.Category
if err := db.Where("slug = ?", slug).Take(&cat).Error; err == nil {
return &cat, nil
}
if locale != "" {
var ids []string
err := db.Session(&gorm.Session{NewDB: true, Context: db.Statement.Context}).
Table(translatemodels.Index{}.TableName()).
Where("model_type = ? AND locale = ? AND item = ? AND value = ?", models.Category{}.MorphName(), locale, "slug", slug).
Order("id ASC").
Pluck("model_id", &ids).Error
if err == nil && len(ids) > 0 {
var translated models.Category
if err := db.Where("CAST(id AS TEXT) IN ?", ids).Order("id ASC").Take(&translated).Error; err == nil {
return &translated, nil
}
}
}
if ctypeDigit(slug) {
return findCategoryByID(db, slug)
}
return nil, gorm.ErrRecordNotFound
}
func findCategoryByID(db *gorm.DB, raw string) (*models.Category, error) {
id, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64)
if err != nil || id == 0 {
return nil, gorm.ErrRecordNotFound
}
var cat models.Category
if err := db.Where("id = ?", id).Take(&cat).Error; err != nil {
return nil, err
}
return &cat, nil
}
func categorySlugTaken(db *gorm.DB, slug string, exceptID uint) bool {
q := db.Model(&models.Category{}).Where("slug = ?", slug)
if exceptID > 0 {
q = q.Where("id <> ?", exceptID)
}
var n int64
_ = q.Count(&n).Error
return n > 0
}
func applyCategoryUpdate(db *gorm.DB, app *backpack.App, cat *models.Category, body map[string]any) map[string][]string {
errs := map[string][]string{}
if _, has := body["name"]; has {
name := strings.TrimSpace(asString(body["name"]))
if name == "" {
errs["name"] = []string{"The name field is required."}
} else if utf8.RuneCountInString(name) > 255 {
errs["name"] = []string{"The name may not be greater than 255 characters."}
} else {
cat.Name = name
}
}
if _, has := body["slug"]; has {
slug := strings.TrimSpace(asString(body["slug"]))
if slug == "" {
errs["slug"] = []string{"The slug field is required."}
} else if !slugPattern.MatchString(slug) {
errs["slug"] = []string{"The slug format is invalid."}
} else if categorySlugTaken(db, slug, cat.ID) {
errs["slug"] = []string{"The slug has already been taken."}
} else {
cat.Slug = slug
}
}
if _, has := body["description"]; has {
if body["description"] == nil {
cat.Description = nil
} else {
desc := strings.TrimSpace(asString(body["description"]))
if desc == "" {
cat.Description = nil
} else {
cat.Description = &desc
}
}
}
if _, has := body["content"]; has {
if body["content"] == nil {
cat.Content = nil
} else {
raw := asString(body["content"])
if strings.TrimSpace(raw) == "" {
cat.Content = nil
} else {
clean := classes.EmbedRegistryFrom(app).SanitizeHTML(raw)
if strings.TrimSpace(clean) == "" {
cat.Content = nil
} else {
cat.Content = &clean
}
}
}
}
if transErr := validateCategoryTranslations(body["translations"]); transErr != nil {
errs["translations"] = []string{transErr.Error()}
}
if len(errs) > 0 {
return errs
}
return nil
}
func validateCategoryTranslations(raw any) error {
if raw == nil {
return nil
}
m, ok := raw.(map[string]any)
if !ok {
return errInvalidCategoryTranslations
}
for _, v := range m {
attrs, ok := v.(map[string]any)
if !ok {
continue
}
if slug := strings.TrimSpace(asString(attrs["slug"])); slug != "" && !slugPattern.MatchString(slug) {
return errInvalidTranslationSlug
}
if name := asString(attrs["name"]); utf8.RuneCountInString(name) > 255 {
return errInvalidTranslationName
}
}
return nil
}
var (
errInvalidCategoryTranslations = categoryValidationError("The translations must be an object.")
errInvalidTranslationSlug = categoryValidationError("The translations slug format is invalid.")
errInvalidTranslationName = categoryValidationError("The translations name may not be greater than 255 characters.")
)
type categoryValidationError string
func (e categoryValidationError) Error() string { return string(e) }
func syncCategoryTranslations(ctx context.Context, db *gorm.DB, cat *models.Category, raw any) error {
m, ok := raw.(map[string]any)
if !ok {
return nil
}
for locale, v := range m {
attrs, ok := v.(map[string]any)
if !ok {
continue
}
for _, field := range []string{"name", "slug", "description"} {
if val, has := attrs[field]; has && val != nil {
if err := translate.SetTranslated(ctx, db, cat, field, locale, val); err != nil {
return err
}
}
}
}
return nil
}
func serializeCategoryDetail(db *gorm.DB, c *models.Category, h1ToH2 bool) map[string]any {
counts := publishedPostCounts(db, "golem15_journal_posts_categories", "category_id")
var desc, content, parent, depth any
if c.Description != nil {
desc = *c.Description
}
if c.Content != nil {
content = *c.Content
}
if c.ParentID != nil {
parent = *c.ParentID
}
if c.NestDepth != nil {
depth = *c.NestDepth
}
return map[string]any{
"id": c.ID,
"name": c.Name,
"slug": c.Slug,
"description": desc,
"content": content,
"parent_id": parent,
"nest_depth": depth,
"post_count": counts[c.ID],
"content_h1_to_h2": h1ToH2,
"translations": categoryTranslationsOf(db, c),
}
}
func categoryTranslationsOf(db *gorm.DB, c *models.Category) any {
if db == nil || c == nil || c.ID == 0 {
return []any{}
}
var locales []struct {
Code string
IsDefault bool
}
if err := db.Table("golem15_translate_locales").
Select("code, is_default").
Where("is_enabled = ?", true).
Find(&locales).Error; err != nil {
return []any{}
}
ctx := db.Statement.Context
if ctx == nil {
ctx = context.Background()
}
out := map[string]any{}
for _, loc := range locales {
if loc.IsDefault {
continue
}
attrs := map[string]any{}
for _, field := range []string{"name", "slug", "description"} {
val, ok, err := translate.TranslatedExact(ctx, db, c, field, loc.Code)
if err != nil || !ok || val == nil {
continue
}
if strings.TrimSpace(asString(val)) == "" {
continue
}
attrs[field] = val
}
if len(attrs) > 0 {
out[loc.Code] = attrs
}
}
if len(out) == 0 {
return []any{}
}
return out
}
type categorySnapshot struct {
name string
slug string
description any
content any
}
func snapshotCategory(c *models.Category) categorySnapshot {
return categorySnapshot{
name: c.Name,
slug: c.Slug,
description: derefValue(c.Description),
content: derefValue(c.Content),
}
}
func categorySavedEvent(ctx context.Context, before categorySnapshot, c *models.Category) pact.RecordSaved {
changes := []pact.RecordChange{}
if before.name != c.Name {
changes = append(changes, pact.RecordChange{Attribute: "name", Old: before.name, New: c.Name})
}
if before.slug != c.Slug {
changes = append(changes, pact.RecordChange{Attribute: "slug", Old: before.slug, New: c.Slug})
}
if nextDesc := derefValue(c.Description); !sameEventValue(before.description, nextDesc) {
changes = append(changes, pact.RecordChange{Attribute: "description", Old: before.description, New: nextDesc})
}
if nextContent := derefValue(c.Content); !sameEventValue(before.content, nextContent) {
changes = append(changes, pact.RecordChange{Attribute: "content", Old: before.content, New: nextContent})
}
locale, _ := towel.Locale(ctx)
return pact.RecordSaved{
Model: c.MorphName(),
ID: strconv.FormatUint(uint64(c.ID), 10),
Locale: locale,
Created: false,
Changes: changes,
}
}

View File

@@ -1,62 +1,126 @@
package api
import (
"reflect"
"sort"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.golem15.com/golem15/sm-journal-plugin/classes"
"git.golem15.com/golem15/sm-journal-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bouncer"
)
func sortedCategoryKeys(row map[string]any) []string {
keys := make([]string, 0, len(row))
for k := range row {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
func TestUpdateCategoryAuthAndPermissions(t *testing.T) {
app := backpack.New(nil)
handler := UpdateCategory(app)
t.Run("unauthenticated returns 401", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPut, "/_journal/api/v1/categories/1", strings.NewReader(`{"name":"News"}`))
req.SetPathValue("id", "1")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401; body = %s", rec.Code, rec.Body.String())
}
})
t.Run("dispatched backend principal without access_categories returns 403", func(t *testing.T) {
pr := &bouncer.Principal{
ID: 7,
Backend: true,
PermissionGrants: map[string]bool{permAccessPosts: true},
}
req := httptest.NewRequest(http.MethodPut, "/_journal/api/v1/categories/1", strings.NewReader(`{"name":"News"}`))
req.SetPathValue("id", "1")
req = req.WithContext(bouncer.WithDispatch(req.Context(), &bouncer.Dispatch{
Principal: pr,
Guards: []string{"backend"},
}))
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403; body = %s", rec.Code, rec.Body.String())
}
})
}
func TestSerializeCategoryNodeContent(t *testing.T) {
html := "<h2>Acme</h2>\n<p>Pillar copy</p>\n"
var parentID uint = 1
root := models.Category{ID: 1, Name: "News", Slug: "news", Content: &html}
child := models.Category{ID: 2, Name: "Quiet", Slug: "quiet", ParentID: &parentID}
byParent := map[uint][]models.Category{1: {child}}
counts := map[uint]int64{1: 2}
row := serializeCategoryNode(&root, byParent, counts, true, true)
if row == nil {
t.Fatal("root row is nil")
func TestApplyCategoryUpdateSanitizationAndValidation(t *testing.T) {
app := backpack.New(nil)
reg := classes.NewEmbedRegistry()
if err := reg.Register(classes.EmbedProvider{
Key: "viz",
Name: "Chart",
IDPattern: `^[a-z0-9-]+$`,
}); err != nil {
t.Fatal(err)
}
if got, ok := row["content"].(string); !ok || got != html {
t.Fatalf("root content = %#v, want %q", row["content"], html)
}
wantRoot := []string{"children", "content", "content_h1_to_h2", "description", "id", "name", "nest_depth", "parent_id", "post_count", "slug"}
if got := sortedCategoryKeys(row); !reflect.DeepEqual(got, wantRoot) {
t.Fatalf("root keys = %v, want %v", got, wantRoot)
}
kids, ok := row["children"].([]map[string]any)
if !ok || len(kids) != 1 {
t.Fatalf("children = %#v, want one row", row["children"])
}
v, present := kids[0]["content"]
if !present || v != nil {
t.Fatalf("child content = %#v (present %v), want nil", v, present)
}
wantChild := []string{"content", "content_h1_to_h2", "description", "id", "name", "nest_depth", "parent_id", "post_count", "slug"}
if got := sortedCategoryKeys(kids[0]); !reflect.DeepEqual(got, wantChild) {
t.Fatalf("child keys = %v, want %v", got, wantChild)
if err := app.Publish(reg); err != nil {
t.Fatal(err)
}
listed := serializeCategoryNode(&root, byParent, counts, false, true)
if listed == nil {
t.Fatal("root omitted without include_empty")
}
if _, has := listed["children"]; has {
t.Fatalf("empty child listed without include_empty: %#v", listed["children"])
}
if got, ok := listed["content"].(string); !ok || got != html {
t.Fatalf("root content without include_empty = %#v, want %q", listed["content"], html)
}
t.Run("sanitizes HTML content with app EmbedRegistry and strips XSS", func(t *testing.T) {
cat := &models.Category{ID: 4, Name: "Old", Slug: "old"}
before := snapshotCategory(cat)
verrs := applyCategoryUpdate(nil, app, cat, map[string]any{
"name": "New Name",
"description": " Short summary ",
"content": `<h2>Intro</h2><script>alert(1)</script><figure data-embed="viz" data-id="chart-1"><img src="/media/abc/c.webp" alt="Chart"></figure>`,
})
if verrs != nil {
t.Fatalf("unexpected validation errors: %v", verrs)
}
if cat.Name != "New Name" {
t.Fatalf("Name = %q, want New Name", cat.Name)
}
if cat.Description == nil || *cat.Description != "Short summary" {
t.Fatalf("Description = %v, want Short summary", cat.Description)
}
if cat.Content == nil {
t.Fatal("Content is nil")
}
if strings.Contains(*cat.Content, "<script") {
t.Fatalf("XSS survived sanitization: %q", *cat.Content)
}
if !strings.Contains(*cat.Content, `data-embed="viz"`) || !strings.Contains(*cat.Content, `data-id="chart-1"`) {
t.Fatalf("registered custom embed lost: %q", *cat.Content)
}
ev := categorySavedEvent(context.Background(), before, cat)
if ev.Model != cat.MorphName() || ev.ID != "4" || ev.Created {
t.Fatalf("unexpected event header: %+v", ev)
}
if len(ev.Changes) != 3 {
t.Fatalf("expected 3 changed attributes (name, description, content), got %+v", ev.Changes)
}
})
t.Run("blank or null content and description clear fields to nil", func(t *testing.T) {
desc := "Old desc"
body := "<p>Old body</p>"
cat := &models.Category{ID: 4, Name: "News", Slug: "news", Description: &desc, Content: &body}
verrs := applyCategoryUpdate(nil, app, cat, map[string]any{
"description": " ",
"content": " \n\t ",
})
if verrs != nil {
t.Fatalf("unexpected validation errors: %v", verrs)
}
if cat.Description != nil || cat.Content != nil {
t.Fatalf("expected nil description & content, got desc=%v content=%v", cat.Description, cat.Content)
}
})
t.Run("rejects empty name and invalid slug format", func(t *testing.T) {
cat := &models.Category{ID: 4, Name: "News", Slug: "news"}
verrs := applyCategoryUpdate(nil, app, cat, map[string]any{
"name": " ",
"slug": "bad slug!",
})
if verrs == nil || len(verrs["name"]) == 0 || len(verrs["slug"]) == 0 {
t.Fatalf("expected name and slug validation errors, got %v", verrs)
}
})
}