Simplify HTTP Basic Authentication middleware

This commit is contained in:
Thorben Günther 2023-07-19 16:00:20 +02:00
parent a908ce78ab
commit c5575c3dc1
No known key found for this signature in database
GPG key ID: 415CD778D8C5AFED

18
main.go
View file

@ -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 {