router.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package telemetry
  2. import (
  3. "net/http"
  4. "github.com/go-chi/chi/v5"
  5. "github.com/go-chi/chi/v5/middleware"
  6. "github.com/go-chi/render"
  7. "github.com/drakkan/sftpgo/v2/common"
  8. "github.com/drakkan/sftpgo/v2/logger"
  9. "github.com/drakkan/sftpgo/v2/metric"
  10. )
  11. func initializeRouter(enableProfiler bool) {
  12. router = chi.NewRouter()
  13. router.Use(middleware.GetHead)
  14. router.Use(middleware.Recoverer)
  15. router.Group(func(r chi.Router) {
  16. r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
  17. render.PlainText(w, r, "ok")
  18. })
  19. })
  20. router.Group(func(router chi.Router) {
  21. router.Use(checkAuth)
  22. metric.AddMetricsEndpoint(metricsPath, router)
  23. if enableProfiler {
  24. logger.InfoToConsole("enabling the built-in profiler")
  25. logger.Info(logSender, "", "enabling the built-in profiler")
  26. router.Mount(pprofBasePath, middleware.Profiler())
  27. }
  28. })
  29. }
  30. func checkAuth(next http.Handler) http.Handler {
  31. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. if !validateCredentials(r) {
  33. w.Header().Set(common.HTTPAuthenticationHeader, "Basic realm=\"SFTPGo telemetry\"")
  34. http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  35. return
  36. }
  37. next.ServeHTTP(w, r)
  38. })
  39. }
  40. func validateCredentials(r *http.Request) bool {
  41. if !httpAuth.IsEnabled() {
  42. return true
  43. }
  44. username, password, ok := r.BasicAuth()
  45. if !ok {
  46. return false
  47. }
  48. return httpAuth.ValidateCredentials(username, password)
  49. }