diff --git a/controllers/api/auth.go b/controllers/api/auth.go index f6d4a03..dc8717c 100644 --- a/controllers/api/auth.go +++ b/controllers/api/auth.go @@ -19,7 +19,10 @@ const ( errPublishPermission = "You do not have permission to publish posts" errEditPermission = "You do not have permission to edit this post" errPostNotFound = "Post not found" + errImageNotFound = "Image not found" errValidationFailed = "Validation failed" + msgPostDeleted = "Post deleted" + msgImageRemoved = "Image removed" permAccessPosts = "golem15.journal.access_posts" permAccessOtherPosts = "golem15.journal.access_other_posts" @@ -32,6 +35,13 @@ func writeAPIError(w http.ResponseWriter, status int, message string) { wire.WriteJSON(w, status, map[string]any{"error": message}) } +func writeValidation(w http.ResponseWriter, errs map[string][]string) { + wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{ + "error": errValidationFailed, + "errors": errs, + }) +} + func writeAuthRequired(w http.ResponseWriter, _ error) { writeAPIError(w, http.StatusUnauthorized, errAuthenticationRequired) } diff --git a/controllers/api/posts.go b/controllers/api/posts.go index 439491c..1c9654f 100644 --- a/controllers/api/posts.go +++ b/controllers/api/posts.go @@ -14,7 +14,9 @@ import ( "git.golem15.com/golem15/summercms/modules/bouncer" "git.golem15.com/golem15/summercms/modules/cabana" "git.golem15.com/golem15/summercms/modules/lagoon" + "git.golem15.com/golem15/summercms/modules/lagoon/attach" "git.golem15.com/golem15/summercms/modules/wire" + "gocloud.dev/blob" "gorm.io/gorm" ) @@ -103,25 +105,79 @@ func Index(app *backpack.App) http.HandlerFunc { } } -// Show is GET /_journal/api/v1/posts/{slug}. Task 2 fills JOURNAL-005. +// Show is GET /_journal/api/v1/posts/{slug}. Numeric slugs fall back to id +// (PHP 192-201). Unpublished or future published_at is 404 with no data key +// unless the caller is the owner or holds access_other_posts (JOURNAL-005). func Show(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { r = optionalBackendPrincipal(app, r) - writeAPIError(w, http.StatusNotFound, errPostNotFound) + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + db = db.WithContext(r.Context()) + slug := strings.TrimSpace(r.PathValue("slug")) + post, err := findPostBySlugOrID(db, slug) + if err != nil || post == nil { + writeAPIError(w, http.StatusNotFound, errPostNotFound) + return + } + pr, _ := bouncer.User(r.Context()) + if !postIsPublished(post) && !canViewDraft(post, pr) { + writeAPIError(w, http.StatusNotFound, errPostNotFound) + return + } + if err := loadPostAssocs(db, post); err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + payload := serializePost(post, db) + payload["previous_post"] = serializeSibling(previousPost(db, post)) + payload["next_post"] = serializeSibling(nextPost(db, post)) + related := relatedPosts(db, post, isEditor(pr)) + rows := make([]map[string]any, 0, len(related)) + for i := range related { + rows = append(rows, serializePost(&related[i], db)) + } + payload["related_posts"] = rows + wire.WriteJSON(w, http.StatusOK, map[string]any{"data": payload}) } } -// Categories is GET /_journal/api/v1/categories. Task 2 fills the PHP list. +// Categories is GET /_journal/api/v1/categories. Empty categories are omitted +// unless ?include_empty=1. func Categories(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - wire.WriteJSON(w, http.StatusOK, map[string]any{"data": []any{}}) + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + includeEmpty := queryBool(r.URL.Query().Get("include_empty")) + data, err := serializeCategoryTree(db.WithContext(r.Context()), includeEmpty) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + wire.WriteJSON(w, http.StatusOK, map[string]any{"data": data}) } } -// Tags is GET /_journal/api/v1/tags. Task 2 fills the PHP list. +// Tags is GET /_journal/api/v1/tags. func Tags(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - wire.WriteJSON(w, http.StatusOK, map[string]any{"data": []any{}}) + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + data, err := serializeTagList(db.WithContext(r.Context())) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + wire.WriteJSON(w, http.StatusOK, map[string]any{"data": data}) } } @@ -134,53 +190,248 @@ func RSS(app *backpack.App) http.HandlerFunc { } } -// Store is POST /_journal/api/v1/posts. Task 2 fills field-by-field create. +// Store is POST /_journal/api/v1/posts. Field-by-field create; never lagoon.Fill. func Store(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if _, _, ok := requireBackendPrincipal(app, w, r); !ok { + r, pr, ok := requireBackendPrincipal(app, w, r) + if !ok { return } - writeAPIError(w, http.StatusForbidden, errInsufficientPerms) + if !requireAccessPosts(w, pr) { + return + } + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + body, err := readJSONObject(r) + if err != nil { + writeAPIError(w, http.StatusBadRequest, errValidationFailed) + return + } + post, verrs := buildNewPost(r, db.WithContext(r.Context()), pr, body) + if verrs != nil { + writeValidation(w, verrs) + return + } + if publishedFlag(body) && !cabana.Allows(pr, []string{permAccessPublish}) { + writeAPIError(w, http.StatusForbidden, errPublishPermission) + return + } + if err := db.WithContext(r.Context()).Create(post).Error; err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + if err := applyPostAssocs(r.Context(), db.WithContext(r.Context()), post, body); err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + if err := loadPostAssocs(db.WithContext(r.Context()), post); err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + wire.WriteJSON(w, http.StatusCreated, map[string]any{"data": serializePost(post, db.WithContext(r.Context()))}) } } -// Update is PUT /_journal/api/v1/posts/{id}. Task 2 fills field-by-field update. +// Update is PUT /_journal/api/v1/posts/{id}. func Update(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if _, _, ok := requireBackendPrincipal(app, w, r); !ok { + r, pr, ok := requireBackendPrincipal(app, w, r) + if !ok { return } - writeAPIError(w, http.StatusForbidden, errInsufficientPerms) + if !requireAccessPosts(w, pr) { + return + } + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + post, err := findPostByID(db.WithContext(r.Context()), r.PathValue("id")) + if err != nil || post == nil { + writeAPIError(w, http.StatusNotFound, errPostNotFound) + return + } + if !post.CanEdit(pr) { + writeAPIError(w, http.StatusForbidden, errEditPermission) + return + } + body, err := readJSONObject(r) + if err != nil { + writeAPIError(w, http.StatusBadRequest, errValidationFailed) + return + } + if verrs := applyPostUpdate(r, db.WithContext(r.Context()), post, body); verrs != nil { + writeValidation(w, verrs) + return + } + if _, has := body["published"]; has && asBool(body["published"]) && !cabana.Allows(pr, []string{permAccessPublish}) { + writeAPIError(w, http.StatusForbidden, errPublishPermission) + return + } + if err := db.WithContext(r.Context()).Save(post).Error; err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + if err := applyPostAssocs(r.Context(), db.WithContext(r.Context()), post, body); err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + if err := loadPostAssocs(db.WithContext(r.Context()), post); err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + wire.WriteJSON(w, http.StatusOK, map[string]any{"data": serializePost(post, db.WithContext(r.Context()))}) } } -// Destroy is DELETE /_journal/api/v1/posts/{id}. Task 2 fills canEdit delete. +// Destroy is DELETE /_journal/api/v1/posts/{id}. func Destroy(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if _, _, ok := requireBackendPrincipal(app, w, r); !ok { + r, pr, ok := requireBackendPrincipal(app, w, r) + if !ok { return } - writeAPIError(w, http.StatusForbidden, errInsufficientPerms) + if !requireAccessPosts(w, pr) { + return + } + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + post, err := findPostByID(db.WithContext(r.Context()), r.PathValue("id")) + if err != nil || post == nil { + writeAPIError(w, http.StatusNotFound, errPostNotFound) + return + } + if !post.CanEdit(pr) { + writeAPIError(w, http.StatusForbidden, errEditPermission) + return + } + if err := db.WithContext(r.Context()).Delete(post).Error; err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + wire.WriteJSON(w, http.StatusOK, map[string]any{"message": msgPostDeleted}) } } // UploadFeaturedImage is POST /_journal/api/v1/posts/{id}/featured-images. func UploadFeaturedImage(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if _, _, ok := requireBackendPrincipal(app, w, r); !ok { + r, pr, ok := requireBackendPrincipal(app, w, r) + if !ok { return } - writeAPIError(w, http.StatusForbidden, errEditPermission) + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + post, err := findPostByID(db.WithContext(r.Context()), r.PathValue("id")) + if err != nil || post == nil { + writeAPIError(w, http.StatusNotFound, errPostNotFound) + return + } + if !post.CanEdit(pr) { + writeAPIError(w, http.StatusForbidden, errEditPermission) + return + } + file, header, err := r.FormFile("file") + if err != nil { + writeValidation(w, map[string][]string{"file": {"The file field is required."}}) + return + } + defer file.Close() + bucket, ok := app.Lookup[*blob.Bucket]() + if !ok || bucket == nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + stored, err := attach.Store(r.Context(), db.WithContext(r.Context()), bucket, attach.Upload{ + FileName: header.Filename, + Body: file, + Public: true, + }, attach.Limits{ + MaxBytes: 10240 << 10, + Image: true, + MIMETypes: []string{"image/jpeg", "image/png", "image/gif", "image/webp"}, + }) + if err != nil { + writeValidation(w, map[string][]string{"file": {err.Error()}}) + return + } + idStr := strconv.FormatUint(uint64(post.ID), 10) + if err := db.WithContext(r.Context()).Model(stored).Updates(map[string]any{ + "attachment_type": post.MorphName(), + "attachment_id": idStr, + "field": "featured_images", + }).Error; err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + stored.AttachmentType = post.MorphName() + stored.AttachmentID = idStr + stored.Field = "featured_images" + wire.WriteJSON(w, http.StatusCreated, map[string]any{ + "data": map[string]any{ + "id": stored.ID, + "url": stored.URL(), + "file_name": stored.FileName, + "file_size": stored.FileSize, + }, + }) } } // DeleteFeaturedImage is DELETE /_journal/api/v1/posts/{id}/featured-images/{fileId}. func DeleteFeaturedImage(app *backpack.App) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - if _, _, ok := requireBackendPrincipal(app, w, r); !ok { + r, pr, ok := requireBackendPrincipal(app, w, r) + if !ok { return } - writeAPIError(w, http.StatusForbidden, errEditPermission) + db, err := gdb(app) + if err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + post, err := findPostByID(db.WithContext(r.Context()), r.PathValue("id")) + if err != nil || post == nil { + writeAPIError(w, http.StatusNotFound, errPostNotFound) + return + } + if !post.CanEdit(pr) { + writeAPIError(w, http.StatusForbidden, errEditPermission) + return + } + fileID, err := strconv.ParseUint(strings.TrimSpace(r.PathValue("fileId")), 10, 64) + if err != nil || fileID == 0 { + writeAPIError(w, http.StatusNotFound, errImageNotFound) + return + } + var file attach.File + err = db.WithContext(r.Context()).Where( + "id = ? AND attachment_type = ? AND attachment_id = ? AND field = ?", + fileID, post.MorphName(), strconv.FormatUint(uint64(post.ID), 10), "featured_images", + ).Take(&file).Error + if err != nil { + writeAPIError(w, http.StatusNotFound, errImageNotFound) + return + } + keys := attach.BlobKeys(file) + if err := db.WithContext(r.Context()).Delete(&file).Error; err != nil { + writeAPIError(w, http.StatusInternalServerError, "Internal server error") + return + } + if bucket, ok := app.Lookup[*blob.Bucket](); ok && bucket != nil { + _ = attach.DeleteKeys(r.Context(), bucket, keys) + } + wire.WriteJSON(w, http.StatusOK, map[string]any{"message": msgImageRemoved}) } } @@ -312,7 +563,7 @@ func serializePost(p *models.Post, db *gorm.DB) map[string]any { "tags": tags, "featured_images": featured, "featured_image_url": featuredURL, - "translations": []any{}, + "translations": translationsOf(db, p), "created_at": carbonTime(p.CreatedAt), "updated_at": carbonTime(p.UpdatedAt), } @@ -331,8 +582,27 @@ func serializeAuthor(user *cabana.BackendUser) any { } } -func featuredImages(_ *gorm.DB, _ *models.Post) []map[string]any { - return []map[string]any{} +func featuredImages(db *gorm.DB, p *models.Post) []map[string]any { + if db == nil || p == nil || p.ID == 0 { + return []map[string]any{} + } + var files []attach.File + if err := db.Where( + "attachment_type = ? AND attachment_id = ? AND field = ?", + p.MorphName(), strconv.FormatUint(uint64(p.ID), 10), "featured_images", + ).Order("sort_order ASC, id ASC").Find(&files).Error; err != nil { + return []map[string]any{} + } + out := make([]map[string]any, 0, len(files)) + for i := range files { + out = append(out, map[string]any{ + "id": files[i].ID, + "url": files[i].URL(), + "file_name": files[i].FileName, + "file_size": files[i].FileSize, + }) + } + return out } func jsonField(raw *string) any { diff --git a/controllers/api/posts_helpers.go b/controllers/api/posts_helpers.go new file mode 100644 index 0000000..970bc6e --- /dev/null +++ b/controllers/api/posts_helpers.go @@ -0,0 +1,778 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" + "time" + "unicode" + "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" + "git.golem15.com/golem15/summercms/modules/bouncer" + "git.golem15.com/golem15/summercms/modules/cabana" + "gorm.io/gorm" +) + +var slugPattern = regexp.MustCompile(`(?i)^[a-z0-9/\:_\-\*\[\]\+\?\|]*$`) + +func postIsPublished(p *models.Post) bool { + if p == nil || !p.Published || p.PublishedAt == nil { + return false + } + return p.PublishedAt.Before(time.Now()) +} + +func canViewDraft(p *models.Post, pr *bouncer.Principal) bool { + if p == nil || pr == nil { + return false + } + if p.UserID != nil && *p.UserID == pr.ID { + return true + } + return cabana.Allows(pr, []string{permAccessOtherPosts}) +} + +func ctypeDigit(s string) bool { + if s == "" { + return false + } + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +} + +func findPostBySlugOrID(db *gorm.DB, slug string) (*models.Post, error) { + q := postQuery(db) + var post models.Post + if err := q.Where("slug = ?", slug).Take(&post).Error; err == nil { + return &post, nil + } + if ctypeDigit(slug) { + id, err := strconv.ParseUint(slug, 10, 64) + if err == nil && id > 0 { + var byID models.Post + if err := postQuery(db).Where("id = ?", id).Take(&byID).Error; err == nil { + return &byID, nil + } + } + } + return nil, gorm.ErrRecordNotFound +} + +func findPostByID(db *gorm.DB, raw string) (*models.Post, error) { + id, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64) + if err != nil || id == 0 { + return nil, gorm.ErrRecordNotFound + } + var post models.Post + if err := postQuery(db).Where("id = ?", id).Take(&post).Error; err != nil { + return nil, err + } + return &post, nil +} + +func postQuery(db *gorm.DB) *gorm.DB { + return db.Model(&models.Post{}).Preload("User").Preload("Categories").Preload("Tags") +} + +func loadPostAssocs(db *gorm.DB, post *models.Post) error { + if post == nil { + return nil + } + return db.Preload("User").Preload("Categories").Preload("Tags").First(post, post.ID).Error +} + +func serializeSibling(p *models.Post) any { + if p == nil { + return nil + } + return map[string]any{"id": p.ID, "title": p.Title, "slug": p.Slug} +} + +func previousPost(db *gorm.DB, p *models.Post) *models.Post { + return siblingPost(db, p, true) +} + +func nextPost(db *gorm.DB, p *models.Post) *models.Post { + return siblingPost(db, p, false) +} + +func siblingPost(db *gorm.DB, p *models.Post, previous bool) *models.Post { + if p == nil { + return nil + } + op, dir := "<", "DESC" + if previous { + op, dir = ">", "ASC" + } + q := applyPublished(db.Model(&models.Post{})).Where("id <> ?", p.ID) + if p.PublishedAt != nil { + q = q.Where( + "(published_at "+op+" ?) OR (published_at = ? AND id "+op+" ?)", + p.PublishedAt, p.PublishedAt, p.ID, + ) + } + var out models.Post + if err := q.Order("published_at " + dir + ", id " + dir).Take(&out).Error; err != nil { + return nil + } + return &out +} + +func relatedPosts(db *gorm.DB, p *models.Post, editor bool) []models.Post { + if p == nil || len(p.Categories) == 0 { + return []models.Post{} + } + ids := make([]uint, 0, len(p.Categories)) + for _, c := range p.Categories { + ids = append(ids, c.ID) + } + q := db.Model(&models.Post{}). + Preload("User").Preload("Categories").Preload("Tags"). + Where("id <> ?", p.ID). + Where("id IN (SELECT post_id FROM golem15_journal_posts_categories WHERE category_id IN (?))", ids) + if !editor { + q = applyPublished(q) + } + var rows []models.Post + if err := q.Order("published_at DESC").Limit(3).Find(&rows).Error; err != nil { + return []models.Post{} + } + return rows +} + +func serializeCategoryTree(db *gorm.DB, includeEmpty bool) ([]map[string]any, error) { + var cats []models.Category + if err := db.Order("nest_left ASC NULLS LAST, id ASC").Find(&cats).Error; err != nil { + return nil, err + } + counts := publishedPostCounts(db, "golem15_journal_posts_categories", "category_id") + byParent := map[uint][]models.Category{} + var roots []models.Category + for _, c := range cats { + if c.ParentID == nil || *c.ParentID == 0 { + roots = append(roots, c) + continue + } + byParent[*c.ParentID] = append(byParent[*c.ParentID], c) + } + out := make([]map[string]any, 0, len(roots)) + for i := range roots { + if row := serializeCategoryNode(&roots[i], byParent, counts, includeEmpty); row != nil { + out = append(out, row) + } + } + return out, nil +} + +func serializeCategoryNode(c *models.Category, byParent map[uint][]models.Category, counts map[uint]int64, includeEmpty bool) map[string]any { + if c == nil { + return nil + } + kids := byParent[c.ID] + childRows := make([]map[string]any, 0, len(kids)) + for i := range kids { + if row := serializeCategoryNode(&kids[i], byParent, counts, includeEmpty); row != nil { + childRows = append(childRows, row) + } + } + postCount := counts[c.ID] + if !includeEmpty && postCount == 0 && len(childRows) == 0 { + return nil + } + var desc any + if c.Description != nil { + desc = *c.Description + } + var parent any + if c.ParentID != nil { + parent = *c.ParentID + } + var depth any + if c.NestDepth != nil { + depth = *c.NestDepth + } + row := map[string]any{ + "id": c.ID, + "name": c.Name, + "slug": c.Slug, + "description": desc, + "parent_id": parent, + "nest_depth": depth, + "post_count": postCount, + } + if len(childRows) > 0 { + row["children"] = childRows + } + return row +} + +func serializeTagList(db *gorm.DB) ([]map[string]any, error) { + var tags []models.Tag + if err := db.Order("name ASC, id ASC").Find(&tags).Error; err != nil { + return nil, err + } + counts := publishedPostCounts(db, "golem15_journal_posts_tags", "tag_id") + out := make([]map[string]any, 0, len(tags)) + for _, tag := range tags { + out = append(out, map[string]any{ + "id": tag.ID, + "name": tag.Name, + "slug": tag.Slug, + "post_count": counts[tag.ID], + }) + } + return out, nil +} + +func publishedPostCounts(db *gorm.DB, pivot, fk string) map[uint]int64 { + type row struct { + ID uint + Count int64 + } + var rows []row + q := fmt.Sprintf( + `SELECT p.%s AS id, COUNT(*) AS count + FROM %s p + INNER JOIN golem15_journal_posts posts ON posts.id = p.post_id + WHERE posts.published = TRUE AND posts.published_at IS NOT NULL AND posts.published_at < ? + GROUP BY p.%s`, + fk, pivot, fk, + ) + _ = db.Raw(q, time.Now()).Scan(&rows).Error + out := map[uint]int64{} + for _, r := range rows { + out[r.ID] = r.Count + } + return out +} + +func translationsOf(db *gorm.DB, p *models.Post) any { + if db == nil || p == nil || p.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{} + } + out := map[string]any{} + for _, loc := range locales { + if loc.IsDefault { + continue + } + attrs := map[string]any{} + ctx := db.Statement.Context + if ctx == nil { + ctx = context.Background() + } + for _, field := range []string{"title", "slug", "content", "content_html", "excerpt", "metadata"} { + val, ok, err := translate.TranslatedExact(ctx, db, p, field, loc.Code) + if err != nil || !ok || val == nil { + continue + } + s := strings.TrimSpace(fmt.Sprint(val)) + if s == "" { + continue + } + attrs[field] = val + } + if len(attrs) > 0 { + out[loc.Code] = attrs + } + } + if len(out) == 0 { + return []any{} + } + return out +} + +func readJSONObject(r *http.Request) (map[string]any, error) { + if r == nil || r.Body == nil { + return map[string]any{}, nil + } + defer r.Body.Close() + raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + return nil, err + } + if len(strings.TrimSpace(string(raw))) == 0 { + return map[string]any{}, nil + } + dec := json.NewDecoder(strings.NewReader(string(raw))) + dec.UseNumber() + var body map[string]any + if err := dec.Decode(&body); err != nil { + return nil, err + } + if body == nil { + body = map[string]any{} + } + return body, nil +} + +func publishedFlag(body map[string]any) bool { + v, ok := body["published"] + if !ok { + return false + } + return asBool(v) +} + +func asBool(v any) bool { + switch t := v.(type) { + case bool: + return t + case json.Number: + n, _ := t.Int64() + return n != 0 + case float64: + return t != 0 + case string: + s := strings.ToLower(strings.TrimSpace(t)) + return s == "1" || s == "true" || s == "on" || s == "yes" + default: + return false + } +} + +func asString(v any) string { + if v == nil { + return "" + } + switch t := v.(type) { + case string: + return t + case json.Number: + return t.String() + default: + return strings.TrimSpace(fmt.Sprint(v)) + } +} + +func asUint(v any) (uint, bool) { + switch t := v.(type) { + case json.Number: + n, err := t.Int64() + if err != nil || n <= 0 { + return 0, false + } + return uint(n), true + case float64: + if t <= 0 || t != float64(uint64(t)) { + return 0, false + } + return uint(t), true + case string: + n, err := strconv.ParseUint(strings.TrimSpace(t), 10, 64) + if err != nil || n == 0 { + return 0, false + } + return uint(n), true + default: + return 0, false + } +} + +func parsePublishedAt(v any) (*time.Time, error) { + if v == nil { + return nil, nil + } + s := strings.TrimSpace(asString(v)) + if s == "" { + return nil, nil + } + for _, layout := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"} { + if ts, err := time.Parse(layout, s); err == nil { + return &ts, nil + } + } + return nil, fmt.Errorf("invalid date") +} + +func jsonPtr(v any) *string { + if v == nil { + return nil + } + switch t := v.(type) { + case string: + s := strings.TrimSpace(t) + if s == "" { + return nil + } + return &s + default: + raw, err := json.Marshal(v) + if err != nil { + return nil + } + s := string(raw) + return &s + } +} + +func slugify(title string) string { + s := strings.ToLower(strings.TrimSpace(title)) + var b strings.Builder + prevDash := false + for _, r := range s { + switch { + case r >= 'a' && r <= 'z', r >= '0' && r <= '9': + b.WriteRune(r) + prevDash = false + case unicode.IsLetter(r) || unicode.IsNumber(r): + b.WriteRune(unicode.ToLower(r)) + prevDash = false + default: + if !prevDash && b.Len() > 0 { + b.WriteByte('-') + prevDash = true + } + } + } + return strings.Trim(b.String(), "-") +} + +func generateUniqueSlug(db *gorm.DB, title string, exceptID uint) string { + base := slugify(title) + if base == "" { + base = "post" + } + slug := base + for n := 1; ; n++ { + q := db.Model(&models.Post{}).Where("slug = ?", slug) + if exceptID > 0 { + q = q.Where("id <> ?", exceptID) + } + var count int64 + _ = q.Count(&count).Error + if count == 0 { + return slug + } + slug = fmt.Sprintf("%s-%d", base, n) + } +} + +func buildNewPost(r *http.Request, db *gorm.DB, pr *bouncer.Principal, body map[string]any) (*models.Post, map[string][]string) { + errs := map[string][]string{} + title := strings.TrimSpace(asString(body["title"])) + if title == "" { + errs["title"] = []string{"The title field is required."} + } else if utf8.RuneCountInString(title) > 255 { + errs["title"] = []string{"The title may not be greater than 255 characters."} + } + content := asString(body["content"]) + if strings.TrimSpace(content) == "" { + errs["content"] = []string{"The content field is required."} + } + slug := strings.TrimSpace(asString(body["slug"])) + if slug == "" { + slug = generateUniqueSlug(db, title, 0) + } else if !slugPattern.MatchString(slug) { + errs["slug"] = []string{"The slug format is invalid."} + } else if slugTaken(db, slug, 0) { + errs["slug"] = []string{"The slug has already been taken."} + } + if _, has := body["published_at"]; has { + if _, err := parsePublishedAt(body["published_at"]); err != nil { + errs["published_at"] = []string{"The published at is not a valid date."} + } + } + if catErr := validateCategoryIDs(db, body["categories"]); catErr != nil { + errs["categories"] = []string{catErr.Error()} + } + if transErr := validateTranslations(body["translations"]); transErr != nil { + errs["translations"] = []string{transErr.Error()} + } + if len(errs) > 0 { + return nil, errs + } + html, err := classes.FormatHTML(content) + if err != nil { + return nil, map[string][]string{"content": {err.Error()}} + } + userID := pr.ID + post := &models.Post{ + Title: title, + Slug: slug, + Content: content, + ContentHTML: html, + Excerpt: strings.TrimSpace(asString(body["excerpt"])), + Published: asBool(body["published"]), + IsPinned: asBool(body["is_pinned"]), + UserID: &userID, + } + if _, has := body["published_at"]; has { + ts, _ := parsePublishedAt(body["published_at"]) + post.PublishedAt = ts + } + if _, has := body["metadata"]; has { + post.Metadata = jsonPtr(body["metadata"]) + } + if _, has := body["sources"]; has { + post.Sources = jsonPtr(body["sources"]) + } + _ = r + return post, nil +} + +func applyPostUpdate(r *http.Request, db *gorm.DB, post *models.Post, body map[string]any) map[string][]string { + errs := map[string][]string{} + if _, has := body["title"]; has { + title := strings.TrimSpace(asString(body["title"])) + if title == "" { + errs["title"] = []string{"The title field is required."} + } else if utf8.RuneCountInString(title) > 255 { + errs["title"] = []string{"The title may not be greater than 255 characters."} + } else { + post.Title = title + } + } + if _, has := body["slug"]; has { + slug := strings.TrimSpace(asString(body["slug"])) + if slug != "" && !slugPattern.MatchString(slug) { + errs["slug"] = []string{"The slug format is invalid."} + } else if slug != "" && slugTaken(db, slug, post.ID) { + errs["slug"] = []string{"The slug has already been taken."} + } else if slug != "" { + post.Slug = slug + } + } + if _, has := body["content"]; has { + content := asString(body["content"]) + if strings.TrimSpace(content) == "" { + errs["content"] = []string{"The content field is required."} + } else { + html, err := classes.FormatHTML(content) + if err != nil { + errs["content"] = []string{err.Error()} + } else { + post.Content = content + post.ContentHTML = html + } + } + } + if _, has := body["excerpt"]; has { + post.Excerpt = strings.TrimSpace(asString(body["excerpt"])) + } + if _, has := body["published"]; has { + post.Published = asBool(body["published"]) + } + if _, has := body["is_pinned"]; has { + post.IsPinned = asBool(body["is_pinned"]) + } + if _, has := body["published_at"]; has { + ts, err := parsePublishedAt(body["published_at"]) + if err != nil { + errs["published_at"] = []string{"The published at is not a valid date."} + } else { + post.PublishedAt = ts + } + } + if _, has := body["metadata"]; has { + post.Metadata = jsonPtr(body["metadata"]) + } + if _, has := body["sources"]; has { + post.Sources = jsonPtr(body["sources"]) + } + if catErr := validateCategoryIDs(db, body["categories"]); catErr != nil { + errs["categories"] = []string{catErr.Error()} + } + if transErr := validateTranslations(body["translations"]); transErr != nil { + errs["translations"] = []string{transErr.Error()} + } + if len(errs) > 0 { + return errs + } + _ = r + return nil +} + +func slugTaken(db *gorm.DB, slug string, exceptID uint) bool { + q := db.Model(&models.Post{}).Where("slug = ?", slug) + if exceptID > 0 { + q = q.Where("id <> ?", exceptID) + } + var n int64 + _ = q.Count(&n).Error + return n > 0 +} + +func validateCategoryIDs(db *gorm.DB, raw any) error { + if raw == nil { + return nil + } + ids, ok := asUintSlice(raw) + if !ok { + return fmt.Errorf("The categories must be an array.") + } + for _, id := range ids { + var n int64 + if err := db.Model(&models.Category{}).Where("id = ?", id).Count(&n).Error; err != nil || n == 0 { + return fmt.Errorf("The selected categories is invalid.") + } + } + return nil +} + +func validateTranslations(raw any) error { + if raw == nil { + return nil + } + m, ok := raw.(map[string]any) + if !ok { + return fmt.Errorf("The translations must be an array.") + } + 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 fmt.Errorf("The translations slug format is invalid.") + } + if title := asString(attrs["title"]); utf8.RuneCountInString(title) > 255 { + return fmt.Errorf("The translations title may not be greater than 255 characters.") + } + } + return nil +} + +func asUintSlice(raw any) ([]uint, bool) { + switch t := raw.(type) { + case []any: + out := make([]uint, 0, len(t)) + for _, item := range t { + id, ok := asUint(item) + if !ok { + return nil, false + } + out = append(out, id) + } + return out, true + default: + return nil, false + } +} + +func applyPostAssocs(ctx context.Context, db *gorm.DB, post *models.Post, body map[string]any) error { + if _, has := body["categories"]; has { + ids, _ := asUintSlice(body["categories"]) + if err := db.Where("post_id = ?", post.ID).Delete(&models.PostCategory{}).Error; err != nil { + return err + } + for _, id := range ids { + if err := db.Create(&models.PostCategory{PostID: post.ID, CategoryID: id}).Error; err != nil { + return err + } + } + } + if _, has := body["tags"]; has { + ids, err := resolveTagIDs(db, body["tags"]) + if err != nil { + return err + } + if err := db.Where("post_id = ?", post.ID).Delete(&models.PostTag{}).Error; err != nil { + return err + } + for _, id := range ids { + if err := db.Create(&models.PostTag{PostID: post.ID, TagID: id}).Error; err != nil { + return err + } + } + } + if raw, has := body["translations"]; has { + if err := syncTranslations(ctx, db, post, raw); err != nil { + return err + } + } + return nil +} + +func resolveTagIDs(db *gorm.DB, raw any) ([]uint, error) { + items, ok := raw.([]any) + if !ok { + if raw == nil { + return nil, nil + } + return nil, fmt.Errorf("tags must be an array") + } + var ids []uint + for _, item := range items { + if id, ok := asUint(item); ok { + var n int64 + if err := db.Model(&models.Tag{}).Where("id = ?", id).Count(&n).Error; err != nil { + return nil, err + } + if n > 0 { + ids = append(ids, id) + } + continue + } + name := strings.TrimSpace(asString(item)) + if name == "" { + continue + } + slug := slugify(name) + var tag models.Tag + err := db.Where("name = ? OR slug = ?", name, slug).Take(&tag).Error + if err == nil { + ids = append(ids, tag.ID) + continue + } + if slug == "" { + slug = "tag" + } + tag = models.Tag{Name: name, Slug: slug} + if err := db.Create(&tag).Error; err != nil { + return nil, err + } + ids = append(ids, tag.ID) + } + return ids, nil +} + +func syncTranslations(ctx context.Context, db *gorm.DB, post *models.Post, raw any) error { + m, ok := raw.(map[string]any) + if !ok { + return nil + } + fields := []string{"title", "slug", "content", "content_html", "excerpt", "metadata"} + for locale, v := range m { + attrs, ok := v.(map[string]any) + if !ok { + continue + } + if content := asString(attrs["content"]); strings.TrimSpace(content) != "" && strings.TrimSpace(asString(attrs["content_html"])) == "" { + html, err := classes.FormatHTML(content) + if err != nil { + return err + } + attrs["content_html"] = html + } + for _, field := range fields { + if val, has := attrs[field]; has && val != nil { + if err := translate.SetTranslated(ctx, db, post, field, locale, val); err != nil { + return err + } + } + } + } + return nil +} diff --git a/journal_api_writes_test.go b/journal_api_writes_test.go new file mode 100644 index 0000000..4e399ac --- /dev/null +++ b/journal_api_writes_test.go @@ -0,0 +1,271 @@ +package journal_test + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "testing" + "time" + + "git.golem15.com/golem15/sm-journal-plugin/controllers" + "git.golem15.com/golem15/sm-journal-plugin/models" + "git.golem15.com/golem15/summercms/modules/bouncer" +) + +func (e *adminEnv) lastUserID(t *testing.T) uint { + t.Helper() + var id uint + if err := e.gdb.Raw(`SELECT id FROM backend_users ORDER BY id DESC LIMIT 1`).Scan(&id).Error; err != nil || id == 0 { + t.Fatalf("last backend user id: id=%d err=%v", id, err) + } + return id +} + +func phpErrorString(t *testing.T, recBody []byte) (string, map[string]any) { + t.Helper() + var body map[string]any + if err := json.Unmarshal(recBody, &body); err != nil { + t.Fatalf("json: %s err=%v", recBody, err) + } + return fmt.Sprint(body["error"]), body +} + +func TestJournalWriteUnauthenticated(t *testing.T) { + env := newPostsEnv(t) + + rec := env.call(t, http.MethodPost, "/_journal/api/v1/posts", "", map[string]any{ + "title": "Nope", + "content": "Body", + }) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("POST without Bearer = %d, want 401: %s", rec.Code, rec.Body.String()) + } + msg, body := phpErrorString(t, rec.Body.Bytes()) + if msg != "Authentication required" { + t.Fatalf("error = %#v, want Authentication required; body=%s", body["error"], rec.Body.String()) + } + if _, isObj := body["error"].(map[string]any); isObj { + t.Fatalf("401 used cabana admin envelope: %s", rec.Body.String()) + } + if _, hasData := body["data"]; hasData { + t.Fatalf("401 must not include data: %s", rec.Body.String()) + } + + front, _, err := bouncer.MintAudience(adminJWTSecret, "1", "https://app.example.test/login", time.Hour, bouncer.AudienceUser) + if err != nil { + t.Fatal(err) + } + denied := env.call(t, http.MethodPost, "/_journal/api/v1/posts", front, map[string]any{ + "title": "Frontend", + "content": "Should not write", + }) + if denied.Code != http.StatusUnauthorized { + t.Fatalf("frontend-audience POST = %d, want 401: %s", denied.Code, denied.Body.String()) + } + if got, _ := phpErrorString(t, denied.Body.Bytes()); got != "Authentication required" { + t.Fatalf("frontend-audience error = %q", got) + } + + limited := env.admin(t, controllers.PermissionAccessPosts) + pubDenied := env.call(t, http.MethodPost, "/_journal/api/v1/posts", limited, map[string]any{ + "title": "Draft publish", + "content": "Cannot publish", + "published": true, + }) + if pubDenied.Code != http.StatusForbidden { + t.Fatalf("publish without access_publish = %d, want 403: %s", pubDenied.Code, pubDenied.Body.String()) + } + if got, _ := phpErrorString(t, pubDenied.Body.Bytes()); got != "You do not have permission to publish posts" { + t.Fatalf("publish error = %q body=%s", got, pubDenied.Body.String()) + } + + okTok := env.admin(t, controllers.PermissionAccessPosts, controllers.PermissionAccessPublish) + created := env.call(t, http.MethodPost, "/_journal/api/v1/posts", okTok, map[string]any{ + "title": "Created post", + "content": "Hello **world**", + }) + if created.Code != http.StatusCreated { + t.Fatalf("authenticated create = %d, want 201: %s", created.Code, created.Body.String()) + } +} + +func TestJournal005DraftShow(t *testing.T) { + env := newPostsEnv(t) + authorTok := env.admin(t, controllers.PermissionAccessPosts) + authorID := env.lastUserID(t) + otherTok := env.admin(t, controllers.PermissionAccessPosts) + privTok := env.admin(t, controllers.PermissionAccessPosts, controllers.PermissionAccessOtherPosts) + + draft := models.Post{ + Title: "Draft for JOURNAL-005", + Slug: "draft-journal-005", + Content: "draft content", + Published: false, + UserID: &authorID, + } + if err := env.gdb.Create(&draft).Error; err != nil { + t.Fatal(err) + } + + anon := env.call(t, http.MethodGet, "/_journal/api/v1/posts/draft-journal-005", "", nil) + if anon.Code != http.StatusNotFound { + t.Fatalf("anonymous draft show = %d, want 404: %s", anon.Code, anon.Body.String()) + } + _, anonBody := phpErrorString(t, anon.Body.Bytes()) + if _, has := anonBody["data"]; has { + t.Fatalf("JOURNAL-005: 404 must not include data: %s", anon.Body.String()) + } + + stranger := env.call(t, http.MethodGet, "/_journal/api/v1/posts/draft-journal-005", otherTok, nil) + if stranger.Code != http.StatusNotFound { + t.Fatalf("stranger draft show = %d, want 404: %s", stranger.Code, stranger.Body.String()) + } + _, strangerBody := phpErrorString(t, stranger.Body.Bytes()) + if _, has := strangerBody["data"]; has { + t.Fatalf("JOURNAL-005 stranger 404 must not include data: %s", stranger.Body.String()) + } + + owner := env.call(t, http.MethodGet, "/_journal/api/v1/posts/draft-journal-005", authorTok, nil) + if owner.Code != http.StatusOK { + t.Fatalf("owner draft show = %d, want 200: %s", owner.Code, owner.Body.String()) + } + var ownerBody struct { + Data struct { + ID uint `json:"id"` + } `json:"data"` + } + if err := json.Unmarshal(owner.Body.Bytes(), &ownerBody); err != nil || ownerBody.Data.ID != draft.ID { + t.Fatalf("owner payload: %s err=%v", owner.Body.String(), err) + } + + byID := env.call(t, http.MethodGet, "/_journal/api/v1/posts/"+strconv.FormatUint(uint64(draft.ID), 10), authorTok, nil) + if byID.Code != http.StatusOK { + t.Fatalf("owner numeric id show = %d, want 200: %s", byID.Code, byID.Body.String()) + } + + priv := env.call(t, http.MethodGet, "/_journal/api/v1/posts/draft-journal-005", privTok, nil) + if priv.Code != http.StatusOK { + t.Fatalf("access_other_posts draft show = %d, want 200: %s", priv.Code, priv.Body.String()) + } +} + +func TestJournalPublicCategories(t *testing.T) { + env := newPostsEnv(t) + left, right, depth := 1, 2, 0 + cat := models.Category{Name: "Essays", Slug: "essays", NestLeft: &left, NestRight: &right, NestDepth: &depth} + if err := env.gdb.Create(&cat).Error; err != nil { + t.Fatal(err) + } + past := time.Now().UTC().Add(-time.Hour) + post := models.Post{Title: "Listed", Slug: "listed-cat", Content: "x", Published: true, PublishedAt: &past} + if err := env.gdb.Create(&post).Error; err != nil { + t.Fatal(err) + } + if err := env.gdb.Create(&models.PostCategory{PostID: post.ID, CategoryID: cat.ID}).Error; err != nil { + t.Fatal(err) + } + + rec := env.call(t, http.MethodGet, "/_journal/api/v1/categories", "", nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET categories = %d, want 200: %s", rec.Code, rec.Body.String()) + } + var body struct { + Data []map[string]any `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("categories json: %s err=%v", rec.Body.String(), err) + } + if len(body.Data) == 0 { + t.Fatalf("categories data empty: %s", rec.Body.String()) + } + row := body.Data[0] + for _, key := range []string{"id", "name", "slug", "description", "parent_id", "nest_depth", "post_count"} { + if _, ok := row[key]; !ok { + t.Fatalf("categories row missing %s: %s", key, rec.Body.String()) + } + } +} + +func TestJournalPublicTags(t *testing.T) { + env := newPostsEnv(t) + tag := models.Tag{Name: "Field notes", Slug: "field-notes"} + if err := env.gdb.Create(&tag).Error; err != nil { + t.Fatal(err) + } + past := time.Now().UTC().Add(-time.Hour) + post := models.Post{Title: "Tagged", Slug: "tagged-row", Content: "x", Published: true, PublishedAt: &past} + if err := env.gdb.Create(&post).Error; err != nil { + t.Fatal(err) + } + if err := env.gdb.Create(&models.PostTag{PostID: post.ID, TagID: tag.ID}).Error; err != nil { + t.Fatal(err) + } + + rec := env.call(t, http.MethodGet, "/_journal/api/v1/tags", "", nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET tags = %d, want 200: %s", rec.Code, rec.Body.String()) + } + var body struct { + Data []map[string]any `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("tags json: %s err=%v", rec.Body.String(), err) + } + if len(body.Data) == 0 { + t.Fatalf("tags data empty: %s", rec.Body.String()) + } + row := body.Data[0] + for _, key := range []string{"id", "name", "slug", "post_count"} { + if _, ok := row[key]; !ok { + t.Fatalf("tags row missing %s: %s", key, rec.Body.String()) + } + } +} + +func TestJournalFeaturedImageUnauthenticated(t *testing.T) { + env := newPostsEnv(t) + authorTok := env.admin(t, controllers.PermissionAccessPosts) + authorID := env.lastUserID(t) + otherTok := env.admin(t, controllers.PermissionAccessPosts) + post := models.Post{Title: "Has images", Slug: "has-images", Content: "x", Published: false, UserID: &authorID} + if err := env.gdb.Create(&post).Error; err != nil { + t.Fatal(err) + } + path := fmt.Sprintf("/_journal/api/v1/posts/%d/featured-images", post.ID) + del := fmt.Sprintf("/_journal/api/v1/posts/%d/featured-images/%d", post.ID, 1) + + anonPost := env.call(t, http.MethodPost, path, "", map[string]any{}) + if anonPost.Code != http.StatusUnauthorized { + t.Fatalf("POST featured-images without Bearer = %d, want 401: %s", anonPost.Code, anonPost.Body.String()) + } + if got, _ := phpErrorString(t, anonPost.Body.Bytes()); got != "Authentication required" { + t.Fatalf("POST featured error = %q body=%s", got, anonPost.Body.String()) + } + + anonDel := env.call(t, http.MethodDelete, del, "", nil) + if anonDel.Code != http.StatusUnauthorized { + t.Fatalf("DELETE featured-images without Bearer = %d, want 401: %s", anonDel.Code, anonDel.Body.String()) + } + if got, _ := phpErrorString(t, anonDel.Body.Bytes()); got != "Authentication required" { + t.Fatalf("DELETE featured error = %q body=%s", got, anonDel.Body.String()) + } + + otherPost := env.call(t, http.MethodPost, path, otherTok, map[string]any{}) + if otherPost.Code != http.StatusForbidden { + t.Fatalf("POST featured as non-editor = %d, want 403: %s", otherPost.Code, otherPost.Body.String()) + } + if got, _ := phpErrorString(t, otherPost.Body.Bytes()); got != "You do not have permission to edit this post" { + t.Fatalf("POST featured 403 = %q body=%s", got, otherPost.Body.String()) + } + + otherDel := env.call(t, http.MethodDelete, del, otherTok, nil) + if otherDel.Code != http.StatusForbidden { + t.Fatalf("DELETE featured as non-editor = %d, want 403: %s", otherDel.Code, otherDel.Body.String()) + } + if got, _ := phpErrorString(t, otherDel.Body.Bytes()); got != "You do not have permission to edit this post" { + t.Fatalf("DELETE featured 403 = %q body=%s", got, otherDel.Body.String()) + } + + _ = authorTok +}