Files
Containr/app/backend/cmd/server/main.go
T
Tomas DvorakandDevin 8b6214a0f5 feat: public platform, admin console, templates, landing docs
Projects become publicly browsable after admin approval; management and
secret-adjacent reads (logs, variables, exec, connection URLs) require
owner/member/admin auth, and platform controls sit behind RequireAdmin.

- Backend: OptionalAuth middleware, read/authed/admin route groups,
  projects.is_approved + service_templates.owner_id migration,
  visibility-aware sqlc queries, admin overview/users/approval endpoints,
  EnsureAdminAccount bootstrap (ADMIN_* env), 30 seeded templates with
  owner CRUD, managed-database connection URLs gated owner+admin, fix
  DB.Stats() infinite recursion.
- Frontend: expandable persisted sidebar + clickable user menu, public
  landing page with searchable docs browser (GitHub sync, bundled
  snapshot + localStorage fallback), DocsBrowser shared with /docs,
  template create/edit/JSON-upload for owned templates, database create
  dialog, admin console (stats, approvals, project edit/delete, user
  admin toggles), HA/Security/Usage polish with dead CSS tokens mapped
  to real theme vars, anonymous-safe gating on every mutation control.
- Tests: safe window.localStorage access fixes happy-dom crashes in
  PlatformShell and canvas storage.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-22 19:58:59 +02:00

168 lines
4.4 KiB
Go

package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"containr/internal/api"
"containr/internal/authruntime"
"containr/internal/config"
"containr/internal/database"
"containr/internal/middleware"
"github.com/gin-gonic/gin"
"github.com/rs/cors"
)
func main() {
// Load configuration
cfg := config.Load()
// Initialize database
db, err := database.NewConnectionWithConfig(cfg.DatabaseURL, database.DBConfig{
MaxOpenConns: cfg.MaxConnections,
MaxIdleConns: cfg.MaxIdleConnections,
ConnMaxLifetime: cfg.ConnMaxLifetime,
ConnMaxIdleTime: cfg.ConnMaxIdleTime,
})
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
defer db.Close()
// Run startup migrations unless explicitly disabled.
if cfg.AutoMigrate {
migrationCtx, migrationCancel := context.WithTimeout(context.Background(), cfg.MigrationLockTimeout)
if err := db.MigrateAllWithLock(migrationCtx, "migrations_goose"); err != nil {
migrationCancel()
log.Fatalf("Failed to run database migrations: %v", err)
}
migrationCancel()
} else {
log.Println("AUTO_MIGRATE disabled; skipping startup migrations")
}
// Seed demo data only when explicitly requested.
if cfg.SeedDataOnStart {
if err := db.SeedData(); err != nil {
log.Printf("Warning: Failed to seed data: %v", err)
}
}
// Initialize Redis
redis, err := database.NewRedis(cfg.RedisURL)
if err != nil {
log.Fatalf("Failed to initialize Redis: %v", err)
}
redisHealthCtx, redisHealthCancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := redis.Health(redisHealthCtx); err != nil {
redisHealthCancel()
log.Fatalf("Failed to connect to Redis: %v", err)
}
redisHealthCancel()
defer redis.Close()
authRuntime, err := authruntime.Start(authruntime.Config{
Enabled: cfg.BetterAuthEnabled,
NodeBinary: cfg.BetterAuthNodeBinary,
Entrypoint: cfg.BetterAuthEntrypoint,
Port: cfg.AuthPort,
StartupTimeout: cfg.BetterAuthStartupTimeout,
})
if err != nil {
log.Fatalf("Failed to start embedded Better Auth runtime: %v", err)
}
if authRuntime != nil {
defer func() {
if closeErr := authRuntime.Close(); closeErr != nil {
log.Printf("Better Auth runtime shutdown error: %v", closeErr)
}
}()
}
// Provision the platform owner account (idempotent, non-fatal).
api.EnsureAdminAccount(context.Background(), db, cfg)
// Setup Gin router
if cfg.IsProduction() {
gin.SetMode(gin.ReleaseMode)
if !cfg.CookieSecure {
log.Println("Warning: COOKIE_SECURE=false in production - session cookies are sent over plain HTTP. Enable TLS and set COOKIE_SECURE=true.")
}
}
router := gin.New()
trustedProxies := []string{}
if cfg.TrustedProxyCIDR != "" {
trustedProxies = []string{cfg.TrustedProxyCIDR}
}
if err := router.SetTrustedProxies(trustedProxies); err != nil {
log.Fatalf("Failed to configure trusted proxies: %v", err)
}
// Add middleware
router.Use(middleware.SecurityHeaders())
router.Use(middleware.Logger())
router.Use(middleware.Recovery())
router.Use(middleware.RequestID())
router.Use(middleware.RequestBodyLimit(cfg.MaxRequestBody))
// CORS setup
c := cors.New(cors.Options{
AllowedOrigins: cfg.CORSOrigins,
AllowedMethods: cfg.CORSMethods,
AllowedHeaders: cfg.CORSHeaders,
ExposedHeaders: []string{"Content-Length"},
AllowCredentials: cfg.CORSCredentials,
MaxAge: 86400,
})
// Wrap Gin router with CORS
handler := c.Handler(router)
// Initialize API routes
api.SetupRoutes(router, db, redis, cfg)
// Create HTTP server
addr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
log.Printf("Server starting on %s", addr)
server := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
}
// Start server in a goroutine
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Failed to start server: %v", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
// Create a deadline for shutdown
ctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
// Attempt graceful shutdown
if err := server.Shutdown(ctx); err != nil {
log.Printf("Server forced to shutdown: %v", err)
}
log.Println("Server exited")
}