SOGOMS v1.0.3 - Admin UI, Cron, Config reload

Phase 13 : sogoms-cron
- Jobs planifiés avec schedule cron standard
- Types: query_email, http, service
- Actions: list, trigger, status

Phase 16 : Réorganisation config/apps/{app}/
- Tous les fichiers d'une app dans un seul dossier
- Migration prokov vers nouvelle structure

Phase 17 : sogoms-admin
- Interface web d'administration (Go templates + htmx)
- Auth sessions cookies signées HMAC-SHA256
- Rôles super_admin / app_admin avec permissions

Phase 19 : Création d'app via Admin UI
- Formulaire création app avec config DB/auth
- Bouton "Scanner la base" : introspection + schema.yaml
- Rechargement automatique sogoway via SIGHUP

Infrastructure :
- sogoctl : socket de contrôle /run/sogoctl.sock
- sogoway : reload config sur SIGHUP sans restart

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-19 20:30:56 +01:00
parent a4694a10d1
commit 65da4efdad
76 changed files with 5305 additions and 80 deletions

View File

@@ -20,7 +20,8 @@ type AppConfig struct {
Database Database `yaml:"database"`
Auth Auth `yaml:"auth"`
Routes []Route `yaml:"routes"`
Queries *Queries // Chargé depuis config/queries/{app}/
Queries *Queries // Chargé depuis config/apps/{app}/queries/
Schema *Schema // Chargé depuis config/apps/{app}/schema.yaml
}
// Queries stocke les requêtes SQL par domaine.
@@ -48,6 +49,14 @@ func (q *Queries) Get(domain, key string) string {
return ""
}
// FileCount retourne le nombre de fichiers de queries chargés.
func (q *Queries) FileCount() int {
if q == nil || q.files == nil {
return 0
}
return len(q.files)
}
// GetMap retourne une map de requêtes (ex: login_data).
func (q *Queries) GetMap(domain, key string) map[string]string {
if q == nil || q.files == nil {
@@ -301,26 +310,33 @@ func NewRegistry(configDir string) *Registry {
}
}
// Load charge toutes les configurations depuis le répertoire routes.
// Load charge toutes les configurations depuis le répertoire apps.
func (r *Registry) Load() error {
r.mu.Lock()
defer r.mu.Unlock()
routesDir := filepath.Join(r.configDir, "routes")
entries, err := os.ReadDir(routesDir)
appsDir := filepath.Join(r.configDir, "apps")
entries, err := os.ReadDir(appsDir)
if err != nil {
return fmt.Errorf("read routes dir: %w", err)
return fmt.Errorf("read apps dir: %w", err)
}
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".yaml") {
if !entry.IsDir() {
continue
}
path := filepath.Join(routesDir, entry.Name())
cfg, err := r.loadAppConfig(path)
appID := entry.Name()
appConfigPath := filepath.Join(appsDir, appID, "app.yaml")
// Vérifier que app.yaml existe
if _, err := os.Stat(appConfigPath); os.IsNotExist(err) {
continue
}
cfg, err := r.loadAppConfig(appConfigPath, appID)
if err != nil {
return fmt.Errorf("load %s: %w", entry.Name(), err)
return fmt.Errorf("load %s: %w", appID, err)
}
r.apps[cfg.App] = cfg
@@ -333,7 +349,7 @@ func (r *Registry) Load() error {
}
// loadAppConfig charge une configuration d'application depuis un fichier YAML.
func (r *Registry) loadAppConfig(path string) (*AppConfig, error) {
func (r *Registry) loadAppConfig(path string, appID string) (*AppConfig, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
@@ -372,15 +388,18 @@ func (r *Registry) loadAppConfig(path string) (*AppConfig, error) {
cfg.Auth.JWTExpiry = "24h"
}
// Charger les requêtes depuis config/queries/{app}/
cfg.Queries = r.loadQueries(cfg.App)
// Charger les requêtes depuis config/apps/{app}/queries/
cfg.Queries = r.loadQueries(appID)
// Charger le schema depuis config/apps/{app}/schema.yaml
cfg.Schema = loadSchema(r.configDir, appID)
return &cfg, nil
}
// loadQueries charge les fichiers de requêtes pour une application.
func (r *Registry) loadQueries(appID string) *Queries {
queriesDir := filepath.Join(r.configDir, "queries", appID)
queriesDir := filepath.Join(r.configDir, "apps", appID, "queries")
entries, err := os.ReadDir(queriesDir)
if err != nil {
return nil // Pas de répertoire queries, c'est OK

255
internal/config/schema.go Normal file
View File

@@ -0,0 +1,255 @@
// Package config - Schema représente la structure de la base de données.
package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// Schema représente le schema d'une application.
type Schema struct {
App string `yaml:"app"`
Version string `yaml:"version"`
Tables map[string]*Table `yaml:"tables"`
}
// Table représente une table de la base de données.
type Table struct {
Columns map[string]*Column `yaml:"columns"`
Primary []string `yaml:"primary,omitempty"` // Clé primaire composite
CRUD []string `yaml:"crud"`
Order string `yaml:"order,omitempty"`
}
// Column représente une colonne d'une table.
type Column struct {
Type string `yaml:"type"`
Length int64 `yaml:"length,omitempty"`
Required bool `yaml:"required,omitempty"`
Primary bool `yaml:"primary,omitempty"`
Auto bool `yaml:"auto,omitempty"`
Unique bool `yaml:"unique,omitempty"`
Default string `yaml:"default,omitempty"`
Foreign string `yaml:"foreign,omitempty"` // table.column
Filter string `yaml:"filter,omitempty"` // "owner" pour filtrage auto
}
// HasCRUD vérifie si une opération CRUD est autorisée pour cette table.
func (t *Table) HasCRUD(op string) bool {
for _, c := range t.CRUD {
if c == op {
return true
}
}
return false
}
// GetOwnerColumn retourne le nom de la colonne avec filter: owner, ou "".
func (t *Table) GetOwnerColumn() string {
for name, col := range t.Columns {
if col.Filter == "owner" {
return name
}
}
return ""
}
// GetPrimaryKey retourne le nom de la clé primaire (simple).
func (t *Table) GetPrimaryKey() string {
// D'abord chercher dans Primary (composite)
if len(t.Primary) == 1 {
return t.Primary[0]
}
// Sinon chercher une colonne avec primary: true
for name, col := range t.Columns {
if col.Primary {
return name
}
}
return "id" // Par défaut
}
// IsCompositePK vérifie si la table a une clé primaire composite.
func (t *Table) IsCompositePK() bool {
return len(t.Primary) > 1
}
// GetSelectColumns retourne la liste des colonnes pour un SELECT.
func (t *Table) GetSelectColumns() []string {
cols := make([]string, 0, len(t.Columns))
for name := range t.Columns {
cols = append(cols, name)
}
return cols
}
// GetInsertColumns retourne les colonnes pour un INSERT (exclut auto-increment).
func (t *Table) GetInsertColumns() []string {
cols := make([]string, 0, len(t.Columns))
for name, col := range t.Columns {
if !col.Auto {
cols = append(cols, name)
}
}
return cols
}
// GetUpdateColumns retourne les colonnes pour un UPDATE (exclut PK et auto).
func (t *Table) GetUpdateColumns() []string {
cols := make([]string, 0, len(t.Columns))
pk := t.GetPrimaryKey()
for name, col := range t.Columns {
if name != pk && !col.Auto && col.Filter != "owner" {
cols = append(cols, name)
}
}
return cols
}
// BuildListQuery génère la requête SELECT pour list.
func (t *Table) BuildListQuery(tableName string) string {
cols := t.GetSelectColumns()
query := fmt.Sprintf("SELECT %s FROM %s", strings.Join(cols, ", "), tableName)
// Ajouter filtre owner si présent
if ownerCol := t.GetOwnerColumn(); ownerCol != "" {
query += fmt.Sprintf(" WHERE %s = ?", ownerCol)
}
// Ajouter ORDER BY si défini
if t.Order != "" {
query += " ORDER BY " + t.Order
}
return query
}
// BuildShowQuery génère la requête SELECT pour show (un seul enregistrement).
func (t *Table) BuildShowQuery(tableName string) string {
cols := t.GetSelectColumns()
pk := t.GetPrimaryKey()
query := fmt.Sprintf("SELECT %s FROM %s WHERE %s = ?", strings.Join(cols, ", "), tableName, pk)
// Ajouter filtre owner si présent
if ownerCol := t.GetOwnerColumn(); ownerCol != "" {
query += fmt.Sprintf(" AND %s = ?", ownerCol)
}
return query
}
// BuildInsertQuery génère la requête INSERT.
func (t *Table) BuildInsertQuery(tableName string, data map[string]any) (string, []any) {
cols := make([]string, 0)
placeholders := make([]string, 0)
args := make([]any, 0)
for name, col := range t.Columns {
if col.Auto {
continue // Skip auto-increment
}
if val, ok := data[name]; ok {
cols = append(cols, name)
placeholders = append(placeholders, "?")
args = append(args, val)
} else if col.Required && col.Default == "" {
// Champ requis sans valeur et sans default - sera une erreur DB
continue
}
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",
tableName,
strings.Join(cols, ", "),
strings.Join(placeholders, ", "))
return query, args
}
// BuildUpdateQuery génère la requête UPDATE.
func (t *Table) BuildUpdateQuery(tableName string, id any, ownerID any, data map[string]any) (string, []any) {
setClauses := make([]string, 0)
args := make([]any, 0)
pk := t.GetPrimaryKey()
ownerCol := t.GetOwnerColumn()
for name := range t.Columns {
// Skip PK, auto, et owner
if name == pk || t.Columns[name].Auto || name == ownerCol {
continue
}
if val, ok := data[name]; ok {
setClauses = append(setClauses, name+" = ?")
args = append(args, val)
}
}
if len(setClauses) == 0 {
return "", nil
}
query := fmt.Sprintf("UPDATE %s SET %s WHERE %s = ?",
tableName,
strings.Join(setClauses, ", "),
pk)
args = append(args, id)
// Ajouter filtre owner
if ownerCol != "" && ownerID != nil {
query += fmt.Sprintf(" AND %s = ?", ownerCol)
args = append(args, ownerID)
}
return query, args
}
// BuildDeleteQuery génère la requête DELETE.
func (t *Table) BuildDeleteQuery(tableName string, id any, ownerID any) (string, []any) {
pk := t.GetPrimaryKey()
query := fmt.Sprintf("DELETE FROM %s WHERE %s = ?", tableName, pk)
args := []any{id}
// Ajouter filtre owner
if ownerCol := t.GetOwnerColumn(); ownerCol != "" && ownerID != nil {
query += fmt.Sprintf(" AND %s = ?", ownerCol)
args = append(args, ownerID)
}
return query, args
}
// ValidateInput valide les données d'entrée selon le schema.
// Retourne les données filtrées (seuls les champs connus sont gardés).
func (t *Table) ValidateInput(data map[string]any) map[string]any {
filtered := make(map[string]any)
for name := range t.Columns {
if val, ok := data[name]; ok {
filtered[name] = val
}
}
return filtered
}
// loadSchema charge le schema depuis config/apps/{app}/schema.yaml.
func loadSchema(configDir, appID string) *Schema {
schemaPath := filepath.Join(configDir, "apps", appID, "schema.yaml")
data, err := os.ReadFile(schemaPath)
if err != nil {
return nil // Pas de schema, c'est OK
}
var schema Schema
if err := yaml.Unmarshal(data, &schema); err != nil {
return nil
}
return &schema
}