From c5575c3dc1e8fc05237738678dabde21ab548309 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Wed, 19 Jul 2023 16:00:20 +0200 Subject: [PATCH] Simplify HTTP Basic Authentication middleware --- main.go | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 748d5eb..74be861 100644 --- a/main.go +++ b/main.go @@ -388,8 +388,8 @@ func (br *bridge) handleWebhooks(w http.ResponseWriter, r *http.Request) { } } -func (br *bridge) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { +func (br *bridge) authMiddleware(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok { br.logger.Debug("basic auth failure") @@ -410,8 +410,8 @@ func (br *bridge) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc return } - handler(w, r) - } + handler.ServeHTTP(w, r) + }) } func (br *bridge) runCleanup(ctx context.Context) { @@ -463,18 +463,16 @@ func main() { logger.Infof("Listening on %s, ntfy-alertmanager %s", cfg.HTTPAddress, version) mux := http.NewServeMux() + mux.HandleFunc("/", bridge.handleWebhooks) + mux.HandleFunc("/silences", bridge.handleSilences) + httpServer := &http.Server{ Addr: cfg.HTTPAddress, Handler: mux, } - if cfg.User != "" && cfg.Password != "" { logger.Info("Enabling HTTP Basic Authentication") - mux.HandleFunc("/", bridge.basicAuthMiddleware(bridge.handleWebhooks)) - mux.HandleFunc("/silences", bridge.basicAuthMiddleware(bridge.handleSilences)) - } else { - mux.HandleFunc("/", bridge.handleWebhooks) - mux.HandleFunc("/silences", bridge.handleSilences) + httpServer.Handler = bridge.authMiddleware(mux) } if _, ok := c.(*cache.MemoryCache); ok {