2024-08-16 09:02:44 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
2024-08-17 13:22:37 +00:00
|
|
|
"strings"
|
2024-08-16 09:02:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
backendNameQueryParam = "connector_id"
|
|
|
|
backendCtxKeyName = "backendName"
|
|
|
|
)
|
|
|
|
|
|
|
|
type BackendFromRequestMiddleware struct {
|
|
|
|
h http.Handler
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *BackendFromRequestMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2024-08-17 13:22:37 +00:00
|
|
|
if !strings.HasPrefix(r.RequestURI, "/authorize") {
|
|
|
|
m.h.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-16 09:02:44 +00:00
|
|
|
if err := r.ParseForm(); err != nil {
|
|
|
|
// TODO: handle this better
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
backendName := r.Form.Get(backendNameQueryParam)
|
|
|
|
// TODO this should be explicitly handled
|
|
|
|
if backendName == "" {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
w.Write([]byte("no backend id provided"))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO we should test that this backend actually exists here
|
|
|
|
|
|
|
|
ctx := context.WithValue(r.Context(), backendCtxKeyName, backendName)
|
|
|
|
m.h.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
}
|
|
|
|
|
|
|
|
func WithBackendFromRequestMiddleware(input http.Handler) http.Handler {
|
|
|
|
return &BackendFromRequestMiddleware{h: input}
|
|
|
|
}
|