middleware.go 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // middleware.go — requireAuth / requireAdmin (paridad auth.js:258-278).
  2. package auth
  3. import (
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "strings"
  8. "github.com/gnacho/netpulse/server-go/internal/db"
  9. )
  10. type ctxKey int
  11. const (
  12. ctxUser ctxKey = iota
  13. ctxSessionID
  14. )
  15. // UserFromContext devuelve el usuario autenticado (nil si no hay).
  16. func UserFromContext(ctx context.Context) *User {
  17. u, _ := ctx.Value(ctxUser).(*User)
  18. return u
  19. }
  20. // SessionIDFromContext devuelve el sessionId autenticado ("" si no hay).
  21. func SessionIDFromContext(ctx context.Context) string {
  22. s, _ := ctx.Value(ctxSessionID).(string)
  23. return s
  24. }
  25. // WriteError escribe el envelope de error {error, message?} con el status dado.
  26. func WriteError(w http.ResponseWriter, status int, code string, message ...string) {
  27. w.Header().Set("Content-Type", "application/json")
  28. w.WriteHeader(status)
  29. body := map[string]any{"error": code}
  30. if len(message) > 0 {
  31. body["message"] = message[0]
  32. }
  33. // json.Marshal (no Encoder): el cuerpo debe ser literal como Hono, SIN
  34. // el '\n' final que añade Encode.
  35. data, _ := json.Marshal(body)
  36. _, _ = w.Write(data)
  37. }
  38. // RequireAuth es middleware global: todo /api/* exige sesión salvo
  39. // /api/health, /api/auth/login, /api/ingest/agent (auth Bearer por token
  40. // de equipo), /api/agents/{slug}/binary (auth Bearer por token de agente,
  41. // Fase 6.2) y /api/agents/{slug}/stream (SSE bidireccional, Fase 7.3).
  42. // Fallo → 401 {error:'unauthorized'}.
  43. func RequireAuth(d *db.DB, secret string, next http.Handler) http.Handler {
  44. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  45. path := r.URL.Path
  46. if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" ||
  47. path == "/api/ingest/agent" ||
  48. (strings.HasPrefix(path, "/api/agents/") && (strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream"))) {
  49. next.ServeHTTP(w, r)
  50. return
  51. }
  52. sess := SessionUserFromRequest(d, secret, r)
  53. if sess == nil {
  54. WriteError(w, http.StatusUnauthorized, "unauthorized")
  55. return
  56. }
  57. ctx := context.WithValue(r.Context(), ctxUser, sess.User)
  58. ctx = context.WithValue(ctx, ctxSessionID, sess.SessionID)
  59. next.ServeHTTP(w, r.WithContext(ctx))
  60. })
  61. }
  62. // RequireAdmin exige role === 'admin' (tras RequireAuth) → 403 {error:'forbidden'}.
  63. func RequireAdmin(next http.Handler) http.Handler {
  64. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  65. user := UserFromContext(r.Context())
  66. if user == nil || user.Role != "admin" {
  67. WriteError(w, http.StatusForbidden, "forbidden")
  68. return
  69. }
  70. next.ServeHTTP(w, r)
  71. })
  72. }