first round of files
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type PipelineHandler struct{}
|
||||
|
||||
func NewPipelineHandler() *PipelineHandler {
|
||||
return &PipelineHandler{}
|
||||
}
|
||||
|
||||
func (h *PipelineHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *PipelineHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type PRHandler struct{}
|
||||
|
||||
func NewPRHandler() *PRHandler {
|
||||
return &PRHandler{}
|
||||
}
|
||||
|
||||
func (h *PRHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *PRHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "created"})
|
||||
}
|
||||
|
||||
func (h *PRHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *PRHandler) Merge(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "merged"})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type RepoHandler struct{}
|
||||
|
||||
func NewRepoHandler() *RepoHandler {
|
||||
return &RepoHandler{}
|
||||
}
|
||||
|
||||
func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "created"})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Tree(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Blob(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"content": ""})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
store sessions.Store
|
||||
}
|
||||
|
||||
func NewUserHandler(store sessions.Store) *UserHandler {
|
||||
return &UserHandler{store: store}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := h.store.Get(r, "fb_session")
|
||||
session.Options.MaxAge = -1
|
||||
session.Save(r, w)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"nhooyr.io/websocket"
|
||||
"nhooyr.io/websocket/wsjson"
|
||||
)
|
||||
|
||||
type WSHandler struct{}
|
||||
|
||||
func NewWSHandler() *WSHandler {
|
||||
return &WSHandler{}
|
||||
}
|
||||
|
||||
func (h *WSHandler) Hub(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
|
||||
OriginPatterns: []string{"localhost:*"},
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
ctx := r.Context()
|
||||
for {
|
||||
var msg map[string]any
|
||||
if err := wsjson.Read(ctx, conn, &msg); err != nil {
|
||||
break
|
||||
}
|
||||
if err := wsjson.Write(ctx, conn, msg); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
ContextKeyUserID contextKey = "userID"
|
||||
ContextKeyUsername contextKey = "username"
|
||||
ContextKeyIsAdmin contextKey = "isAdmin"
|
||||
)
|
||||
|
||||
type AuthMiddleware struct {
|
||||
store sessions.Store
|
||||
}
|
||||
|
||||
func NewAuth(store sessions.Store) *AuthMiddleware {
|
||||
return &AuthMiddleware{store: store}
|
||||
}
|
||||
|
||||
func (a *AuthMiddleware) Require(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, err := a.store.Get(r, "fb_session")
|
||||
if err != nil || session.IsNew {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := session.Values["userID"].(int64)
|
||||
if !ok || userID == 0 {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), ContextKeyUserID, userID)
|
||||
if username, ok := session.Values["username"].(string); ok {
|
||||
ctx = context.WithValue(ctx, ContextKeyUsername, username)
|
||||
}
|
||||
if isAdmin, ok := session.Values["isAdmin"].(bool); ok {
|
||||
ctx = context.WithValue(ctx, ContextKeyIsAdmin, isAdmin)
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthMiddleware) Optional(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, err := a.store.Get(r, "fb_session")
|
||||
if err == nil && !session.IsNew {
|
||||
if userID, ok := session.Values["userID"].(int64); ok && userID != 0 {
|
||||
ctx := context.WithValue(r.Context(), ContextKeyUserID, userID)
|
||||
r = r.WithContext(ctx)
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func UserIDFromContext(ctx context.Context) (int64, bool) {
|
||||
id, ok := ctx.Value(ContextKeyUserID).(int64)
|
||||
return id, ok
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func RequireAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
isAdmin, _ := r.Context().Value(ContextKeyIsAdmin).(bool)
|
||||
if !isAdmin {
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user