first round of files

This commit is contained in:
2026-05-06 23:13:06 +02:00
parent a30962474d
commit 2aa5d01307
24 changed files with 991 additions and 0 deletions
+118
View File
@@ -0,0 +1,118 @@
package api
import (
"io/fs"
"net/http"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
gcsrf "github.com/gorilla/csrf"
"github.com/gorilla/sessions"
"github.com/forgao/forgebucket/internal/api/handlers"
"github.com/forgao/forgebucket/internal/api/middleware"
"github.com/forgao/forgebucket/internal/config"
)
func New(cfg *config.Config, store sessions.Store, staticFiles fs.FS) http.Handler {
r := chi.NewRouter()
r.Use(chimiddleware.Logger)
r.Use(chimiddleware.RealIP)
r.Use(chimiddleware.Recoverer)
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"http://localhost:5173", cfg.InstanceURL},
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
MaxAge: 300,
}))
csrfMiddleware := gcsrf.Protect(
[]byte(cfg.CSRFSecret),
gcsrf.Secure(!cfg.Debug),
gcsrf.SameSite(gcsrf.SameSiteLaxMode),
gcsrf.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "CSRF validation failed", http.StatusForbidden)
})),
)
auth := middleware.NewAuth(store)
repoH := handlers.NewRepoHandler()
userH := handlers.NewUserHandler(store)
prH := handlers.NewPRHandler()
pipeH := handlers.NewPipelineHandler()
wsH := handlers.NewWSHandler()
// Health check (no auth, no CSRF)
r.Get("/api/v1/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
})
// CSRF token endpoint for SPA bootstrap
r.With(csrfMiddleware).Get("/api/v1/csrf", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-CSRF-Token", gcsrf.Token(r))
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"ok":true}`))
})
// Auth routes (CSRF protected, no session required)
r.With(csrfMiddleware).Route("/api/v1/auth", func(r chi.Router) {
r.Post("/login", userH.Login)
r.Post("/logout", userH.Logout)
})
// Authenticated API routes
r.With(csrfMiddleware).With(auth.Require).Route("/api/v1", func(r chi.Router) {
r.Get("/me", userH.Me)
r.Route("/repos", func(r chi.Router) {
r.Get("/", repoH.List)
r.Post("/", repoH.Create)
r.Route("/{owner}/{repo}", func(r chi.Router) {
r.Get("/", repoH.Get)
r.Get("/tree", repoH.Tree)
r.Get("/blob", repoH.Blob)
r.Route("/pulls", func(r chi.Router) {
r.Get("/", prH.List)
r.Post("/", prH.Create)
r.Get("/{prID}", prH.Get)
r.Post("/{prID}/merge", prH.Merge)
})
r.Route("/pipelines", func(r chi.Router) {
r.Get("/", pipeH.List)
r.Get("/{runID}", pipeH.Get)
})
})
})
})
// WebSocket hub (auth via session cookie, no CSRF needed for WS)
r.With(auth.Optional).Get("/ws", wsH.Hub)
// SPA fallback — serve embedded React app for all other routes
r.Handle("/*", spaHandler(staticFiles))
return r
}
func spaHandler(staticFiles fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(staticFiles))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := staticFiles.Open(r.URL.Path)
if err != nil {
// Unknown path → serve index.html for client-side routing
index, err := staticFiles.Open("index.html")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
index.Close()
r.URL.Path = "/"
}
fileServer.ServeHTTP(w, r)
})
}