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)) }