model

package
v0.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2026 License: GPL-3.0 Imports: 7 Imported by: 0

Documentation

Overview

Package model defines domain models and types used throughout the application.

Package model contains domain models and constants for the application.

Package model defines domain models and types used throughout the application including User, Page, Event, and configuration structures.

Package model defines domain models and types used throughout the application.

Index

Constants

View Source
const (
	PermissionPagesRead     = "pages:read"
	PermissionPagesWrite    = "pages:write"
	PermissionMediaRead     = "media:read"
	PermissionMediaWrite    = "media:write"
	PermissionTaxonomyRead  = "taxonomy:read"
	PermissionTaxonomyWrite = "taxonomy:write"
)

API permissions

View Source
const (
	ConfigTypeString = "string"
	ConfigTypeInt    = "int"
	ConfigTypeBool   = "bool"
	ConfigTypeText   = "text" // multi-line text, renders as textarea
)

Config types

View Source
const (
	ConfigKeySiteName            = "site_name"
	ConfigKeySiteDescription     = "site_description"
	ConfigKeySiteURL             = "site_url"
	ConfigKeyDefaultOGImage      = "default_og_image"
	ConfigKeyAdminEmail          = "admin_email"
	ConfigKeyPostsPerPage        = "posts_per_page"
	ConfigKeyPoweredBy           = "powered_by"
	ConfigKeyCopyright           = "copyright"
	ConfigKeyExcludedIPs         = "excluded_ips"
	ConfigKeyRobotsContentSignal = "robots_content_signal"
	ConfigKeyMCPServerVersion    = "mcp_server_version"
)

Config keys

View Source
const (
	EventLevelInfo    = "info"
	EventLevelWarning = "warning"
	EventLevelError   = "error"
)

Event levels

View Source
const (
	EventCategoryAuth      = "auth"
	EventCategoryPage      = "page"
	EventCategoryUser      = "user"
	EventCategoryConfig    = "config"
	EventCategorySystem    = "system"
	EventCategoryCache     = "cache"
	EventCategoryMigrator  = "migrator"
	EventCategoryMedia     = "media"
	EventCategoryTag       = "tag"
	EventCategoryCategory  = "category"
	EventCategoryMenu      = "menu"
	EventCategoryAPIKey    = "api_key"
	EventCategoryWebhook   = "webhook"
	EventCategorySecurity  = "security"
	EventCategoryScheduler = "scheduler"
)

Event categories

View Source
const (
	FieldTypeText     = "text"
	FieldTypeEmail    = "email"
	FieldTypeTextarea = "textarea"
	FieldTypeNumber   = "number"
	FieldTypeSelect   = "select"
	FieldTypeRadio    = "radio"
	FieldTypeCheckbox = "checkbox"
	FieldTypeDate     = "date"
	FieldTypeFile     = "file"
	FieldTypeCaptcha  = "captcha"
)

Form field type constants

View Source
const (
	DirectionLTR = "ltr"
	DirectionRTL = "rtl"
)

Language text directions

View Source
const (
	VariantThumbnail = "thumbnail"
	VariantGrid      = "grid"
	VariantSmall     = "small"
	VariantMedium    = "medium"
	VariantLarge     = "large"
	VariantOG        = "og"
)

Supported image variant types

View Source
const (
	MinFeaturedImageWidth  = 1200
	MinFeaturedImageHeight = 800
)

Minimum dimensions for featured images

View Source
const (
	MimeTypeJPEG = "image/jpeg"
	MimeTypePNG  = "image/png"
	MimeTypeGIF  = "image/gif"
	MimeTypeWebP = "image/webp"
	MimeTypeICO  = "image/x-icon"
	MimeTypePDF  = "application/pdf"
	MimeTypeMP4  = "video/mp4"
	MimeTypeWebM = "video/webm"
)

Supported MIME types

View Source
const (
	MenuMain   = "main"
	MenuFooter = "footer"
)

Default menu slugs

View Source
const (
	TargetSelf   = "_self"
	TargetBlank  = "_blank"
	TargetParent = "_parent"
	TargetTop    = "_top"
)

Menu target values

View Source
const (
	PageStatusDraft     = "draft"
	PageStatusPublished = "published"
)

Page statuses

View Source
const (
	EntityTypePage     = "page"
	EntityTypeCategory = "category"
	EntityTypeTag      = "tag"
	EntityTypeForm     = "form"
)

Entity types for translations

View Source
const (
	RoleAnonymous = "anonymous" // Not logged in (used for cache context)
	RoleAdmin     = "admin"     // Full system access
	RoleEditor    = "editor"    // Content management access
	RolePublic    = "public"    // No admin access
)

User role constants.

View Source
const (
	EventPageCreated     = "page.created"
	EventPageUpdated     = "page.updated"
	EventPageDeleted     = "page.deleted"
	EventPagePublished   = "page.published"
	EventPageUnpublished = "page.unpublished"
	EventMediaUploaded   = "media.uploaded"
	EventMediaDeleted    = "media.deleted"
	EventFormSubmitted   = "form.submitted"
	EventUserCreated     = "user.created"
	EventUserDeleted     = "user.deleted"
)

Webhook event types

View Source
const (
	DeliveryStatusPending   = "pending"
	DeliveryStatusDelivered = "delivered"
	DeliveryStatusFailed    = "failed"
	DeliveryStatusDead      = "dead"
)

Webhook delivery statuses

View Source
const APIKeyPrefixLength = 4

APIKeyPrefixLength is the number of characters used for the key prefix. Reduced from 8 to 4 to preserve more entropy in the key.

Variables

View Source
var CommonLanguages = []struct {
	Code       string
	Name       string
	NativeName string
	Direction  string
}{
	{Code: "en", Name: "English", NativeName: "English", Direction: "ltr"},
	{Code: "ru", Name: "Russian", NativeName: "Русский", Direction: "ltr"},
	{Code: "de", Name: "German", NativeName: "Deutsch", Direction: "ltr"},
	{Code: "fr", Name: "French", NativeName: "Français", Direction: "ltr"},
	{Code: "es", Name: "Spanish", NativeName: "Español", Direction: "ltr"},
	{Code: "it", Name: "Italian", NativeName: "Italiano", Direction: "ltr"},
	{Code: "pt", Name: "Portuguese", NativeName: "Português", Direction: "ltr"},
	{Code: "nl", Name: "Dutch", NativeName: "Nederlands", Direction: "ltr"},
	{Code: "pl", Name: "Polish", NativeName: "Polski", Direction: "ltr"},
	{Code: "uk", Name: "Ukrainian", NativeName: "Українська", Direction: "ltr"},
	{Code: "zh", Name: "Chinese", NativeName: "中文", Direction: "ltr"},
	{Code: "ja", Name: "Japanese", NativeName: "日本語", Direction: "ltr"},
	{Code: "ko", Name: "Korean", NativeName: "한국어", Direction: "ltr"},
	{Code: "ar", Name: "Arabic", NativeName: "العربية", Direction: "rtl"},
	{Code: "he", Name: "Hebrew", NativeName: "עברית", Direction: "rtl"},
	{Code: "fa", Name: "Persian", NativeName: "فارسی", Direction: "rtl"},
	{Code: "tr", Name: "Turkish", NativeName: "Türkçe", Direction: "ltr"},
	{Code: "vi", Name: "Vietnamese", NativeName: "Tiếng Việt", Direction: "ltr"},
	{Code: "th", Name: "Thai", NativeName: "ไทย", Direction: "ltr"},
	{Code: "hi", Name: "Hindi", NativeName: "हिन्दी", Direction: "ltr"},
}

CommonLanguages provides a list of commonly used languages for selection UI.

View Source
var ImageVariants = map[string]ImageVariantConfig{
	VariantThumbnail: {Width: 150, Height: 150, Quality: 80, Crop: true},
	VariantGrid:      {Width: 256, Height: 256, Quality: 85, Crop: true},
	VariantSmall:     {Width: 400, Height: 300, Quality: 85, Crop: false},
	VariantMedium:    {Width: 800, Height: 600, Quality: 85, Crop: false},
	VariantLarge:     {Width: 1920, Height: 1080, Quality: 90, Crop: false},
	VariantOG:        {Width: 1200, Height: 630, Quality: 85, Crop: false},
}

ImageVariants defines the default image variant configurations.

View Source
var StandardConfigFields = []ConfigFieldDefinition{
	{Key: ConfigKeySiteName, DefaultValue: "Opossum CMS", Type: ConfigTypeString, Description: "The name of your site"},
	{Key: ConfigKeySiteDescription, DefaultValue: "", Type: ConfigTypeString, Description: "A short description of your site"},
	{Key: ConfigKeySiteURL, DefaultValue: "", Type: ConfigTypeString, Description: "Full site URL for canonical links and OG tags (e.g., https://example.com)"},
	{Key: ConfigKeyDefaultOGImage, DefaultValue: "", Type: ConfigTypeString, Description: "Default Open Graph image URL for social sharing (1200x630px recommended)"},
	{Key: ConfigKeyCopyright, DefaultValue: "", Type: ConfigTypeString, Description: "Footer copyright text (leave empty for automatic)"},
	{Key: ConfigKeyPoweredBy, DefaultValue: "Powered by oCMS", Type: ConfigTypeString, Description: "Footer powered by text"},
	{Key: ConfigKeyPostsPerPage, DefaultValue: "10", Type: ConfigTypeInt, Description: "Number of posts to display per page"},
	{Key: ConfigKeyAdminEmail, DefaultValue: "admin@example.com", Type: ConfigTypeString, Description: "Administrator email address"},
	{Key: ConfigKeyExcludedIPs, DefaultValue: "", Type: ConfigTypeText, Description: "IPs or CIDRs to exclude from analytics and event logging (one per line)"},
	{Key: ConfigKeyRobotsContentSignal, DefaultValue: "", Type: ConfigTypeString, Description: "robots.txt Content-Signal directive (contentsignals.org). Leave empty for the default 'search=yes, ai-train=no, ai-input=yes', or set to 'off' / 'none' / 'disabled' to suppress."},
	{Key: ConfigKeyMCPServerVersion, DefaultValue: "", Type: ConfigTypeString, Description: "Version string advertised in /.well-known/mcp/server-card.json (leave empty to omit)"},
}

StandardConfigFields defines all config fields that should always be shown, even on a newly created site without seeding. These fields are displayed in the admin config page and can be edited by administrators.

TranslatableConfigKeys is the list of config keys that support per-language translations.

ValidRoles contains all valid user roles for form validation.

ValidTargets contains all valid link target values.

Functions

func AllPermissions

func AllPermissions() []string

AllPermissions returns all available API permissions.

func AllSupportedTypes

func AllSupportedTypes() []string

AllSupportedTypes returns all supported MIME types.

func CheckAPIKeyHash added in v0.1.0

func CheckAPIKeyHash(key, encodedHash string) bool

CheckAPIKeyHash verifies an API key against its Argon2id hash. Uses constant-time comparison to prevent timing attacks.

func EventsToJSON

func EventsToJSON(events []string) string

EventsToJSON converts a slice of events to a JSON string.

func ExtractAPIKeyPrefix added in v0.1.0

func ExtractAPIKeyPrefix(rawKey string) string

ExtractAPIKeyPrefix extracts the prefix from a raw API key.

func GenerateAPIKey

func GenerateAPIKey() (rawKey string, prefix string, err error)

GenerateAPIKey generates a new random API key. Returns the raw key (to show user once) and the key prefix.

func GenerateWebhookSecret

func GenerateWebhookSecret() (string, error)

GenerateWebhookSecret generates a random secret for webhook signing.

func HashAPIKey

func HashAPIKey(key string) (string, error)

HashAPIKey creates an Argon2id hash of the API key for storage. Returns encoded hash string in format: $argon2id$v=19$m=65536,t=1,p=4$salt$hash

func HeadersToJSON

func HeadersToJSON(headers map[string]string) string

HeadersToJSON converts a map of headers to a JSON string.

func IsSupportedMimeType

func IsSupportedMimeType(mimeType string) bool

IsSupportedMimeType checks if a MIME type is supported.

func IsTranslatableConfigKey

func IsTranslatableConfigKey(key string) bool

IsTranslatableConfigKey checks if a config key supports translations.

func IsValidFieldType

func IsValidFieldType(fieldType string) bool

IsValidFieldType checks if a field type is valid.

func IsValidTarget

func IsValidTarget(target string) bool

IsValidTarget checks if a target value is valid.

func PermissionsToJSON

func PermissionsToJSON(perms []string) string

PermissionsToJSON converts a slice of permissions to a JSON string.

func SupportedDocumentTypes

func SupportedDocumentTypes() []string

SupportedDocumentTypes returns a list of supported document MIME types.

func SupportedImageTypes

func SupportedImageTypes() []string

SupportedImageTypes returns a list of supported image MIME types.

func SupportedVideoTypes

func SupportedVideoTypes() []string

SupportedVideoTypes returns a list of supported video MIME types.

func ValidFieldTypes

func ValidFieldTypes() []string

ValidFieldTypes returns all valid form field types.

Types

type APIKey

type APIKey struct {
	ID          int64        `json:"id"`
	Name        string       `json:"name"`
	KeyHash     string       `json:"-"` // Never expose hash in JSON
	KeyPrefix   string       `json:"key_prefix"`
	Permissions string       `json:"-"` // JSON array stored as string
	LastUsedAt  sql.NullTime `json:"last_used_at,omitempty"`
	ExpiresAt   sql.NullTime `json:"expires_at,omitempty"`
	IsActive    bool         `json:"is_active"`
	CreatedBy   int64        `json:"created_by"`
	CreatedAt   time.Time    `json:"created_at"`
	UpdatedAt   time.Time    `json:"updated_at"`
}

APIKey represents an API authentication key.

func (*APIKey) GetPermissions

func (k *APIKey) GetPermissions() []string

GetPermissions parses the JSON permissions string into a slice.

func (*APIKey) HasAnyPermission

func (k *APIKey) HasAnyPermission(perms ...string) bool

HasAnyPermission checks if the API key has any of the specified permissions.

func (*APIKey) HasPermission

func (k *APIKey) HasPermission(perm string) bool

HasPermission checks if the API key has a specific permission.

func (*APIKey) IsExpired

func (k *APIKey) IsExpired() bool

IsExpired checks if the API key has expired.

func (*APIKey) IsValid

func (k *APIKey) IsValid() bool

IsValid checks if the API key is active and not expired.

type Config

type Config struct {
	Key         string
	Value       string
	Type        string
	Description string
	UpdatedAt   time.Time
	UpdatedBy   sql.NullInt64
}

Config represents a site configuration item.

type ConfigFieldDefinition added in v0.4.0

type ConfigFieldDefinition struct {
	Key          string
	DefaultValue string
	Type         string
	Description  string
}

ConfigFieldDefinition defines a standard config field with its metadata.

type Event

type Event struct {
	ID         int64
	Level      string
	Category   string
	Message    string
	UserID     sql.NullInt64
	Metadata   string // JSON string
	IPAddress  string
	RequestURL string
	CreatedAt  time.Time
}

Event represents a system event log entry.

type ImageVariantConfig

type ImageVariantConfig struct {
	Width   int
	Height  int
	Quality int
	Crop    bool // true = crop to exact size, false = fit within bounds
}

ImageVariantConfig defines settings for generating image variants.

type Language

type Language struct {
	ID         int64     `json:"id"`
	Code       string    `json:"code"`        // ISO 639-1: en, ru, de, fr
	Name       string    `json:"name"`        // English, Russian, German, French
	NativeName string    `json:"native_name"` // English, Русский, Deutsch, Français
	IsDefault  bool      `json:"is_default"`  // only one can be default
	IsActive   bool      `json:"is_active"`   // enabled for site
	Direction  string    `json:"direction"`   // ltr, rtl
	Position   int       `json:"position"`    // sort order in language switcher
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

Language represents a content/UI language in the CMS.

func (*Language) IsRTL

func (l *Language) IsRTL() bool

IsRTL returns true if the language is right-to-left.

type Media

type Media struct {
	ID         int64
	UUID       string
	Filename   string
	MimeType   string
	Size       int64
	Width      sql.NullInt64
	Height     sql.NullInt64
	Alt        string
	Caption    string
	FolderID   sql.NullInt64
	UploadedBy int64
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Media represents an uploaded file in the media library.

func (*Media) IsImage

func (m *Media) IsImage() bool

IsImage returns true if the media type is an image.

func (*Media) IsPDF

func (m *Media) IsPDF() bool

IsPDF returns true if the media type is a PDF document.

func (*Media) IsVideo

func (m *Media) IsVideo() bool

IsVideo returns true if the media type is a video.

type MediaFolder

type MediaFolder struct {
	ID        int64
	Name      string
	ParentID  sql.NullInt64
	Position  int64
	CreatedAt time.Time
}

MediaFolder represents a folder in the media library.

type MediaVariant

type MediaVariant struct {
	ID        int64
	MediaID   int64
	Type      string
	Width     int64
	Height    int64
	Size      int64
	CreatedAt time.Time
}

MediaVariant represents a generated variant of an image.

type Menu struct {
	ID        int64
	Name      string
	Slug      string
	CreatedAt time.Time
	UpdatedAt time.Time
}

Menu represents a navigation menu.

type MenuItem struct {
	ID        int64
	MenuID    int64
	ParentID  sql.NullInt64
	Title     string
	URL       string
	Target    string
	PageID    sql.NullInt64
	Position  int
	CSSClass  string
	IsActive  bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

MenuItem represents an item in a navigation menu.

type MenuItemWithChildren struct {
	MenuItem
	Children []MenuItemWithChildren
}

MenuItemWithChildren represents a menu item with its children for tree display.

type Page

type Page struct {
	ID          int64        `json:"id"`
	Title       string       `json:"title"`
	Slug        string       `json:"slug"`
	Body        string       `json:"body"`
	Status      string       `json:"status"`
	AuthorID    int64        `json:"author_id"`
	CreatedAt   time.Time    `json:"created_at"`
	UpdatedAt   time.Time    `json:"updated_at"`
	PublishedAt sql.NullTime `json:"published_at,omitempty"`
}

Page represents a CMS page.

func (*Page) IsDraft

func (p *Page) IsDraft() bool

IsDraft returns true if the page is a draft.

func (*Page) IsPublished

func (p *Page) IsPublished() bool

IsPublished returns true if the page is published.

type PageVersion

type PageVersion struct {
	ID        int64     `json:"id"`
	PageID    int64     `json:"page_id"`
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	ChangedBy int64     `json:"changed_by"`
	CreatedAt time.Time `json:"created_at"`
}

PageVersion represents a historical version of a page.

type Translation

type Translation struct {
	ID            int64     `json:"id"`
	EntityType    string    `json:"entity_type"`    // page, category, tag, menu_item
	EntityID      int64     `json:"entity_id"`      // ID of the source entity
	LanguageID    int64     `json:"language_id"`    // Language this translation is for
	TranslationID int64     `json:"translation_id"` // ID of the translated entity
	CreatedAt     time.Time `json:"created_at"`
}

Translation represents a link between content entities across languages. For example, Page 1 (English) linked to Page 2 (Russian) would be: Translation { EntityType: "page", EntityID: 1, LanguageID: 2, TranslationID: 2 }

type TranslationLink struct {
	LanguageID   int64  `json:"language_id"`
	LanguageCode string `json:"language_code"`
	LanguageName string `json:"language_name"`
	NativeName   string `json:"native_name"`
	EntityID     int64  `json:"entity_id"` // The translated entity ID
	Exists       bool   `json:"exists"`    // Whether translation exists
}

TranslationLink represents a simplified view of a translation for UI purposes.

type TranslationWithLanguage

type TranslationWithLanguage struct {
	Translation
	LanguageCode       string `json:"language_code"`
	LanguageName       string `json:"language_name"`
	LanguageNativeName string `json:"language_native_name"`
}

TranslationWithLanguage includes language information for display purposes.

type User

type User struct {
	ID           int64        `json:"id"`
	Email        string       `json:"email"`
	PasswordHash string       `json:"-"` // Never expose in JSON
	Role         string       `json:"role"`
	Name         string       `json:"name"`
	CreatedAt    time.Time    `json:"created_at"`
	UpdatedAt    time.Time    `json:"updated_at"`
	LastLoginAt  sql.NullTime `json:"last_login_at,omitempty"`
}

User represents a CMS user.

func (*User) IsAdmin

func (u *User) IsAdmin() bool

IsAdmin returns true if the user has admin role.

type Webhook

type Webhook struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	URL       string    `json:"url"`
	Secret    string    `json:"-"` // Never expose in JSON
	Events    string    `json:"-"` // JSON array stored as string
	IsActive  bool      `json:"is_active"`
	Headers   string    `json:"-"` // JSON object stored as string
	CreatedBy int64     `json:"created_by"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Webhook represents a webhook configuration.

func (*Webhook) GetEvents

func (w *Webhook) GetEvents() []string

GetEvents parses the JSON events string into a slice.

func (*Webhook) GetHeaders

func (w *Webhook) GetHeaders() map[string]string

GetHeaders parses the JSON headers string into a map.

func (*Webhook) HasEvent

func (w *Webhook) HasEvent(event string) bool

HasEvent checks if the webhook is subscribed to a specific event.

func (*Webhook) SetEvents

func (w *Webhook) SetEvents(events []string)

SetEvents sets the events from a slice to JSON string.

func (*Webhook) SetHeaders

func (w *Webhook) SetHeaders(headers map[string]string)

SetHeaders sets the headers from a map to JSON string.

type WebhookDelivery

type WebhookDelivery struct {
	ID           int64         `json:"id"`
	WebhookID    int64         `json:"webhook_id"`
	Event        string        `json:"event"`
	Payload      string        `json:"payload"`
	ResponseCode sql.NullInt64 `json:"response_code,omitempty"`
	ResponseBody string        `json:"response_body,omitempty"`
	Attempts     int64         `json:"attempts"`
	NextRetryAt  sql.NullTime  `json:"next_retry_at,omitempty"`
	DeliveredAt  sql.NullTime  `json:"delivered_at,omitempty"`
	Status       string        `json:"status"`
	ErrorMessage string        `json:"error_message,omitempty"`
	CreatedAt    time.Time     `json:"created_at"`
	UpdatedAt    time.Time     `json:"updated_at"`
}

WebhookDelivery represents a webhook delivery attempt.

func (*WebhookDelivery) GetPayload

func (d *WebhookDelivery) GetPayload() map[string]interface{}

GetPayload parses the JSON payload string into a map.

func (*WebhookDelivery) IsDead

func (d *WebhookDelivery) IsDead() bool

IsDead returns true if the delivery has exhausted all retries.

func (*WebhookDelivery) IsDelivered

func (d *WebhookDelivery) IsDelivered() bool

IsDelivered returns true if the delivery was successful.

func (*WebhookDelivery) IsFailed

func (d *WebhookDelivery) IsFailed() bool

IsFailed returns true if the delivery failed but may retry.

func (*WebhookDelivery) IsPending

func (d *WebhookDelivery) IsPending() bool

IsPending returns true if the delivery is pending.

type WebhookEventInfo

type WebhookEventInfo struct {
	Type        string
	Description string
}

WebhookEventInfo contains event type and description.

func AllWebhookEvents

func AllWebhookEvents() []WebhookEventInfo

AllWebhookEvents returns all available webhook event types with descriptions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL