From a6c41b2aac0b3495046baa62e63a60186e73643f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Mon, 10 Oct 2022 19:55:33 +0200 Subject: [PATCH] Use middleware for basic auth --- main.go | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/main.go b/main.go index b94524a..2fad806 100644 --- a/main.go +++ b/main.go @@ -34,19 +34,6 @@ type alert struct { } func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) { - if rcv.cfg.User != "" && rcv.cfg.Password != "" { - user, pass, ok := r.BasicAuth() - if !ok { - rcv.logger.Debug("basic auth failure") - return - } - - if user != rcv.cfg.User || pass != rcv.cfg.Password { - rcv.logger.Debug("basic auth: wrong user or password") - return - } - } - defer r.Body.Close() if r.Method != http.MethodPost { @@ -121,6 +108,23 @@ func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) { } } +func (rcv *receiver) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + user, pass, ok := r.BasicAuth() + if !ok { + rcv.logger.Debug("basic auth failure") + return + } + + if user != rcv.cfg.User || pass != rcv.cfg.Password { + rcv.logger.Debug("basic auth: wrong user or password") + return + } + + handler(w, r) + } +} + func main() { var configPath string flag.StringVar(&configPath, "config", "/etc/ntfy-alertmanager/config", "config file path") @@ -139,7 +143,14 @@ func main() { receiver := &receiver{cfg: cfg, logger: logger} - http.HandleFunc("/", receiver.handleWebhooks) logger.Infof("Listening on %s", cfg.HTTPAddress) + + if cfg.User != "" && cfg.Password != "" { + logger.Info("Enabling HTTP Basic Authentication") + http.HandleFunc("/", receiver.basicAuthMiddleware(receiver.handleWebhooks)) + } else { + http.HandleFunc("/", receiver.handleWebhooks) + } + logger.Fatal(http.ListenAndServe(cfg.HTTPAddress, nil)) }