Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
63 lines
2.0 KiB
Go
63 lines
2.0 KiB
Go
package graph
|
|
|
|
// Hand-written helpers for page.resolvers.go and box.resolvers.go, kept out
|
|
// of the resolver files for the same reason as box_helpers.go.
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"adam-french.co.uk/backend/models"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// Slugs are URL-safe as they stand.
|
|
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
|
|
|
|
const maxSlugLen = 100
|
|
|
|
// Paths Caddy or the SPA's routes answer first, plus "index". "shrines" and
|
|
// "stp" are canvas pages, so not reserved.
|
|
var reservedFirstSegments = map[string]bool{
|
|
"stp2": true, "index": true, "admin": true, "cv": true,
|
|
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
|
|
"gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true,
|
|
"usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true,
|
|
"sound": true, "assets": true, "internal": true, "dozzle": true, "garage": true,
|
|
}
|
|
|
|
func validPageKey(key string) bool {
|
|
return len(key) <= maxSlugLen && pageKeyPattern.MatchString(key)
|
|
}
|
|
|
|
// validateSlug reports why slug can't be a page's address, or nil.
|
|
func validateSlug(slug string) error {
|
|
if !validPageKey(slug) {
|
|
return errors.New("a page address is lower-case letters, digits and hyphens, in /-separated parts, e.g. shrines/evangelion")
|
|
}
|
|
first, _, _ := strings.Cut(slug, "/")
|
|
if reservedFirstSegments[first] {
|
|
return errors.New("that address is already used by the site")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// A key with no Page row is never hidden.
|
|
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
|
|
if IsAdminFromCtx(ctx) {
|
|
return false, nil
|
|
}
|
|
var count int64
|
|
err := db.Model(&models.Page{}).Where("slug = ? AND admin_only = ?", key, true).Count(&count).Error
|
|
return count > 0, err
|
|
}
|
|
|
|
// Checked up front for a readable error; the partial unique index backs it.
|
|
func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) {
|
|
var count int64
|
|
err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error
|
|
return count > 0, err
|
|
}
|