1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
package main
import (
"context"
"html/template"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/alexedwards/scs/sqlite3store"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/joho/godotenv"
"task-dashboard/internal/api"
"task-dashboard/internal/auth"
"task-dashboard/internal/config"
"task-dashboard/internal/handlers"
appmiddleware "task-dashboard/internal/middleware"
"task-dashboard/internal/store"
)
func main() {
// Load .env file (ignore error if file doesn't exist - env vars might be set directly)
_ = godotenv.Load()
// Load configuration
cfg, err := config.Load()
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
// Initialize database
db, err := store.New(cfg.DatabasePath, cfg.MigrationDir)
if err != nil {
log.Fatalf("Failed to initialize database: %v", err)
}
defer func() { _ = db.Close() }()
// Initialize session manager
sessionManager := scs.New()
sessionManager.Store = sqlite3store.New(db.DB())
sessionManager.Lifetime = config.SessionLifetime
sessionManager.Cookie.Persist = true
sessionManager.Cookie.Secure = !cfg.Debug
sessionManager.Cookie.SameSite = http.SameSiteLaxMode
// Initialize auth service
authService := auth.NewService(db.DB())
// Ensure default admin user exists (use env vars for credentials)
defaultUser := os.Getenv("DEFAULT_USER")
defaultPass := os.Getenv("DEFAULT_PASS")
if defaultUser == "" {
defaultUser = "admin"
}
if defaultPass == "" {
log.Fatal("CRITICAL: DEFAULT_PASS environment variable must be set. Cannot start without a password.")
}
if err := authService.EnsureDefaultUser(defaultUser, defaultPass); err != nil {
log.Printf("Warning: failed to ensure default user: %v", err)
}
// Parse templates for auth handlers
authTemplates, err := template.ParseGlob(filepath.Join(cfg.TemplateDir, "*.html"))
if err != nil {
log.Printf("Warning: failed to parse auth templates: %v", err)
}
// Initialize auth handlers
authHandlers := auth.NewHandlers(authService, sessionManager, authTemplates)
// Initialize API clients
todoistClient := api.NewTodoistClient(cfg.TodoistAPIKey)
trelloClient := api.NewTrelloClient(cfg.TrelloAPIKey, cfg.TrelloToken)
var planToEatClient api.PlanToEatAPI
if cfg.HasPlanToEat() {
pteClient := api.NewPlanToEatClient(cfg.PlanToEatAPIKey)
if cfg.PlanToEatSession != "" {
pteClient.SetSessionCookie(cfg.PlanToEatSession)
}
planToEatClient = pteClient
}
var googleCalendarClient api.GoogleCalendarAPI
if cfg.HasGoogleCalendar() {
// Use timeout context to prevent startup hangs if credentials file is unreachable
initCtx, cancel := context.WithTimeout(context.Background(), config.GoogleCalendarInitTimeout)
var err error
googleCalendarClient, err = api.NewGoogleCalendarClient(initCtx, cfg.GoogleCredentialsFile, cfg.GoogleCalendarID)
cancel()
if err != nil {
log.Printf("Warning: failed to initialize Google Calendar client: %v", err)
} else {
log.Printf("Google Calendar client initialized for calendars: %s", cfg.GoogleCalendarID)
}
}
// Initialize handlers
h := handlers.New(db, todoistClient, trelloClient, planToEatClient, googleCalendarClient, cfg)
// Set up router
r := chi.NewRouter()
// Global middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(config.RequestTimeout))
r.Use(appmiddleware.SecurityHeaders(cfg.Debug)) // Security headers
r.Use(sessionManager.LoadAndSave) // Session middleware must be applied globally
r.Use(authHandlers.Middleware().CSRFProtect) // CSRF protection
// Rate limiter for auth endpoints
authRateLimiter := appmiddleware.NewRateLimiter(config.AuthRateLimitRequests, config.AuthRateLimitWindow)
// Public routes (no auth required)
r.Get("/login", authHandlers.HandleLoginPage)
r.With(authRateLimiter.Limit).Post("/login", authHandlers.HandleLogin)
r.Post("/logout", authHandlers.HandleLogout)
// Serve static files (public)
fileServer := http.FileServer(http.Dir(cfg.StaticDir))
r.Handle("/static/*", http.StripPrefix("/static/", fileServer))
// Protected routes (auth required)
r.Group(func(r chi.Router) {
r.Use(authHandlers.Middleware().RequireAuth)
// Dashboard
r.Get("/", h.HandleDashboard)
r.Get("/conditions", h.HandleConditionsPage)
r.Post("/api/refresh", h.HandleRefresh)
r.Get("/api/tasks", h.HandleGetTasks)
r.Get("/api/meals", h.HandleGetMeals)
r.Get("/api/boards", h.HandleGetBoards)
r.Get("/api/shopping", h.HandleGetShoppingList)
// Tab routes for HTMX
r.Get("/tabs/tasks", h.HandleTabTasks)
r.Get("/tabs/planning", h.HandleTabPlanning)
r.Get("/tabs/meals", h.HandleTabMeals)
r.Get("/tabs/timeline", h.HandleTimeline)
r.Get("/tabs/shopping", h.HandleTabShopping)
r.Get("/tabs/conditions", h.HandleTabConditions)
r.Post("/tabs/refresh", h.HandleRefreshTab)
// Trello card operations
r.Post("/cards", h.HandleCreateCard)
r.Post("/cards/complete", h.HandleCompleteCard)
// Todoist task operations
r.Post("/tasks", h.HandleCreateTask)
r.Post("/tasks/complete", h.HandleCompleteTask)
// Unified task completion (for Tasks tab Atoms)
r.Post("/complete-atom", h.HandleCompleteAtom)
r.Post("/uncomplete-atom", h.HandleUncompleteAtom)
// Unified Quick Add (for Tasks tab)
r.Post("/unified-add", h.HandleUnifiedAdd)
r.Get("/partials/lists", h.HandleGetListsOptions)
r.Get("/partials/shopping-lists", h.HandleGetShoppingLists)
// Task detail/edit
r.Get("/tasks/detail", h.HandleGetTaskDetail)
r.Post("/tasks/update", h.HandleUpdateTask)
// Bug reporting
r.Get("/bugs", h.HandleGetBugs)
r.Post("/bugs", h.HandleReportBug)
// Shopping quick-add
r.Post("/shopping/add", h.HandleShoppingQuickAdd)
r.Post("/shopping/toggle", h.HandleShoppingToggle)
})
// Start server
addr := ":" + cfg.Port
srv := &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Graceful shutdown
go func() {
log.Printf("Starting server on http://localhost%s", addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server failed: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
// Graceful shutdown with timeout
ctx, cancel := context.WithTimeout(context.Background(), config.GracefulShutdownTimeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
log.Println("Server exited")
}
|