server auth

This commit is contained in:
2026-05-28 08:35:50 -04:00
parent 3d44a392f1
commit fc63f9c44a
37 changed files with 3877 additions and 74 deletions

View File

@@ -1,11 +1,9 @@
package httpserver
import (
"context"
"encoding/json"
"net/http"
"os"
"strings"
"github.com/go-chi/chi/v5"
@@ -24,9 +22,13 @@ func (s *Server) handleSyncInit(w http.ResponseWriter, r *http.Request) {
return
}
userID := r.Context().Value("userID").(string)
principal, ok := requirePrincipal(r)
if !ok {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
return
}
snapshot, err := s.syncService.InitSync(r.Context(), req.DeviceID, userID)
snapshot, err := s.syncService.InitSync(r.Context(), req.DeviceID, principal.UserID)
if err != nil {
s.logger.Error("sync init failed", "error", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to initialize sync"})
@@ -112,30 +114,3 @@ func (s *Server) handleContentFetch(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(content)
}
func (s *Server) apiKeyMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip for non-sync routes
if !strings.HasPrefix(r.URL.Path, "/api/sync/") && !strings.HasPrefix(r.URL.Path, "/api/content/") {
next.ServeHTTP(w, r)
return
}
apiKey := r.Header.Get("X-API-Key")
if apiKey == "" {
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "missing API key"})
return
}
// Validate API key against database
record, err := s.syncRepo.ValidateAPIKey(r.Context(), apiKey)
if err != nil {
s.logger.Warn("invalid api key", "error", err)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid API key"})
return
}
ctx := context.WithValue(r.Context(), "userID", record.UserID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}