middleware.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package api
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/smallstep/certificates/api"
  6. "github.com/smallstep/certificates/authority/admin"
  7. )
  8. type nextHTTP = func(http.ResponseWriter, *http.Request)
  9. // requireAPIEnabled is a middleware that ensures the Administration API
  10. // is enabled before servicing requests.
  11. func (h *Handler) requireAPIEnabled(next nextHTTP) nextHTTP {
  12. return func(w http.ResponseWriter, r *http.Request) {
  13. if !h.auth.IsAdminAPIEnabled() {
  14. api.WriteError(w, admin.NewError(admin.ErrorNotImplementedType,
  15. "administration API not enabled"))
  16. return
  17. }
  18. next(w, r)
  19. }
  20. }
  21. // extractAuthorizeTokenAdmin is a middleware that extracts and caches the bearer token.
  22. func (h *Handler) extractAuthorizeTokenAdmin(next nextHTTP) nextHTTP {
  23. return func(w http.ResponseWriter, r *http.Request) {
  24. tok := r.Header.Get("Authorization")
  25. if len(tok) == 0 {
  26. api.WriteError(w, admin.NewError(admin.ErrorUnauthorizedType,
  27. "missing authorization header token"))
  28. return
  29. }
  30. adm, err := h.auth.AuthorizeAdminToken(r, tok)
  31. if err != nil {
  32. api.WriteError(w, err)
  33. return
  34. }
  35. ctx := context.WithValue(r.Context(), adminContextKey, adm)
  36. next(w, r.WithContext(ctx))
  37. }
  38. }
  39. // ContextKey is the key type for storing and searching for ACME request
  40. // essentials in the context of a request.
  41. type ContextKey string
  42. const (
  43. // adminContextKey account key
  44. adminContextKey = ContextKey("admin")
  45. )