Use middleware for basic auth

This commit is contained in:
Thorben Günther 2022-10-10 19:55:33 +02:00
parent 61ed59cefa
commit a6c41b2aac
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED

39
main.go
View file

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