aboutsummaryrefslogtreecommitdiff
path: root/internal/httputil/httpapi.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/httputil/httpapi.go')
-rw-r--r--internal/httputil/httpapi.go32
1 files changed, 30 insertions, 2 deletions
diff --git a/internal/httputil/httpapi.go b/internal/httputil/httpapi.go
index c78aadf8..0559fbb7 100644
--- a/internal/httputil/httpapi.go
+++ b/internal/httputil/httpapi.go
@@ -15,6 +15,7 @@
package httputil
import (
+ "encoding/json"
"fmt"
"io"
"net/http"
@@ -44,6 +45,7 @@ type BasicAuth struct {
type AuthAPIOpts struct {
GuestAccessAllowed bool
+ WithAuth bool
}
// AuthAPIOption is an option to MakeAuthAPI to add additional checks (e.g. guest access) to verify
@@ -57,6 +59,13 @@ func WithAllowGuests() AuthAPIOption {
}
}
+// WithAuth is an option to MakeHTTPAPI to add authentication.
+func WithAuth() AuthAPIOption {
+ return func(opts *AuthAPIOpts) {
+ opts.WithAuth = true
+ }
+}
+
// MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which authenticates the request.
func MakeAuthAPI(
metricsName string, userAPI userapi.QueryAcccessTokenAPI,
@@ -197,13 +206,32 @@ func MakeExternalAPI(metricsName string, f func(*http.Request) util.JSONResponse
return http.HandlerFunc(withSpan)
}
-// MakeHTMLAPI adds Span metrics to the HTML Handler function
+// MakeHTTPAPI adds Span metrics to the HTML Handler function
// This is used to serve HTML alongside JSON error messages
-func MakeHTMLAPI(metricsName string, enableMetrics bool, f func(http.ResponseWriter, *http.Request)) http.Handler {
+func MakeHTTPAPI(metricsName string, userAPI userapi.QueryAcccessTokenAPI, enableMetrics bool, f func(http.ResponseWriter, *http.Request), checks ...AuthAPIOption) http.Handler {
withSpan := func(w http.ResponseWriter, req *http.Request) {
trace, ctx := internal.StartTask(req.Context(), metricsName)
defer trace.EndTask()
req = req.WithContext(ctx)
+
+ // apply additional checks, if any
+ opts := AuthAPIOpts{}
+ for _, opt := range checks {
+ opt(&opts)
+ }
+
+ if opts.WithAuth {
+ logger := util.GetLogger(req.Context())
+ _, jsonErr := auth.VerifyUserFromRequest(req, userAPI)
+ if jsonErr != nil {
+ w.WriteHeader(jsonErr.Code)
+ if err := json.NewEncoder(w).Encode(jsonErr.JSON); err != nil {
+ logger.WithError(err).Error("failed to encode JSON response")
+ }
+ return
+ }
+ }
+
f(w, req)
}