feat: add user credentials management and health monitoring features
- Implemented CredentialsDialog for updating user credentials. - Created auth store with functions for managing authentication state. - Added HealthWidget to display server health status. - Introduced health monitoring functionality with polling. - Developed AppShell layout to manage authentication and loading states. - Added SettingsDialog for user preferences including theme and language. - Created utility functions for list management and data fetching. - Implemented dashboard view mode preferences. - Integrated search functionality for filtering lists. - Established theme management with local storage support. - Added utility functions for class name management. - Configured SvelteKit for static site generation with fallback. - Set up Vite for development with proxy support for API calls. - Created About and List detail pages with data fetching and display. - Added favicon and updated project configuration files.
This commit is contained in:
1 parent
a4a3eeb5cc
commit
6c1ea2da47
80 files changed
No files matched your search
@@ -0,0 +1,276 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
)
|
||||
|
||||
// The SvelteKit build is copied here by the Docker builder before go build.
|
||||
// Keeping a tiny tracked placeholder in web/ also lets go test run from a
|
||||
// checkout before the dashboard has been built.
|
||||
//
|
||||
//go:embed all:web
|
||||
var webFS embed.FS
|
||||
|
||||
type Server struct {
|
||||
db *DB
|
||||
auth *AuthService
|
||||
startTime time.Time
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := envOrDefault("PORT", "3000")
|
||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||
if connectionString == "" {
|
||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
database, err := connectWithRetry(ctx, connectionString)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer database.close()
|
||||
go database.pruneExpiredSessions(ctx)
|
||||
go database.cleanupNotifications(ctx)
|
||||
|
||||
auth := newAuthService(database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
|
||||
server := &Server{db: database, auth: auth, startTime: time.Now()}
|
||||
|
||||
webRoot, err := fs.Sub(webFS, "web")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webRoot)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: withCORS(mux),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
|
||||
interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond
|
||||
if interval < 250*time.Millisecond {
|
||||
interval = 250 * time.Millisecond
|
||||
}
|
||||
maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0)
|
||||
|
||||
for attempt := int64(1); ; attempt++ {
|
||||
database, err := connectDB(ctx, connectionString)
|
||||
if err == nil {
|
||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||
if attempt > 1 {
|
||||
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
|
||||
}
|
||||
return database, nil
|
||||
} else {
|
||||
database.close()
|
||||
err = schemaErr
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||
if maxAttempts > 0 && attempt >= maxAttempts {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("[DB] Retrying in %s...\n", interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(interval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
// Health and auth bootstrap routes are intentionally public.
|
||||
mux.HandleFunc("GET /health", s.handleHealth)
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
|
||||
mux.Handle("POST /api/auth/logout", s.auth.requireSession(s.auth.handleLogout))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate))
|
||||
|
||||
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
||||
// user's devices. This is deliberately separate from browser sessions.
|
||||
api := func(handler http.Handler) http.Handler {
|
||||
return s.auth.requireAPIToken(handler)
|
||||
}
|
||||
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("GET /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
mux.Handle("PUT /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
mux.Handle("DELETE /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
|
||||
mux.Handle("POST /api/fields", api(http.HandlerFunc(s.handleFieldCollection)))
|
||||
mux.Handle("GET /api/fields/list/{listId}", api(http.HandlerFunc(s.handleFieldsForList)))
|
||||
mux.Handle("PUT /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
|
||||
mux.Handle("DELETE /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
|
||||
|
||||
mux.Handle("POST /api/items", api(http.HandlerFunc(s.handleItemCollection)))
|
||||
mux.Handle("POST /api/items/values", api(http.HandlerFunc(s.handleItemValueCollection)))
|
||||
// These item paths overlap under the Go ServeMux pattern rules (for
|
||||
// example /items/list/values), so dispatch the legacy subroutes in one
|
||||
// prefix handler while keeping /items/values exact for POST.
|
||||
mux.Handle("/api/items/", api(http.HandlerFunc(s.handleItemPath)))
|
||||
|
||||
mux.Handle("POST /api/sync", api(http.HandlerFunc(s.handleSync)))
|
||||
mux.Handle("GET /api/notifications/poll", api(http.HandlerFunc(s.handleNotificationPoll)))
|
||||
|
||||
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
|
||||
// are protected by the browser session.
|
||||
mux.Handle("GET /web/info", s.auth.requireSession(s.handleWebInfo))
|
||||
mux.Handle("GET /web/data", s.auth.requireSession(s.handleWebData))
|
||||
mux.Handle("/", spaFileServer(webRoot))
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
func envOrDefault(name, fallback string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt64(name string, fallback int64) int64 {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
var parsed int64
|
||||
if _, err := fmt.Sscan(value, &parsed); err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{
|
||||
"error": message,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
func withCORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func spaFileServer(root fs.FS) http.Handler {
|
||||
fileServer := http.FileServer(http.FS(root))
|
||||
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := fs.ReadFile(root, "index.html")
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
||||
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
if _, err := fs.Stat(root, cleanPath); err != nil {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type dependency struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type techStackResponse struct {
|
||||
AppVersion string `json:"appVersion"`
|
||||
Stack []stackEntry `json:"stack"`
|
||||
}
|
||||
|
||||
type stackEntry struct {
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (s *Server) handleWebInfo(w http.ResponseWriter, _ *http.Request, _ *AuthUser) {
|
||||
writeJSON(w, http.StatusOK, techStackResponse{
|
||||
AppVersion: envOrDefault("APP_VERSION", "dev"),
|
||||
Stack: []stackEntry{
|
||||
{Label: "Runtime", Value: "Go " + runtime.Version()},
|
||||
{Label: "Language", Value: "Go " + runtime.Version()},
|
||||
{Label: "Web Framework", Value: "net/http"},
|
||||
{Label: "Database", Value: "PostgreSQL (pgx/v5)"},
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user