2020-02-29 08:15:12 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/ncarlier/webhookd/pkg/auth"
|
|
|
|
)
|
|
|
|
|
2023-02-13 21:17:46 +00:00
|
|
|
const xWebAuthUser = "X-WebAuth-User"
|
|
|
|
|
2020-02-29 08:15:12 +00:00
|
|
|
// AuthN is a middleware to checks HTTP request credentials
|
|
|
|
func AuthN(authenticator auth.Authenticator) Middleware {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2023-02-13 21:17:46 +00:00
|
|
|
w.Header().Del(xWebAuthUser)
|
|
|
|
if ok, username := authenticator.Validate(r); ok {
|
2023-10-03 20:57:14 +00:00
|
|
|
w.Header().Set(xWebAuthUser, username)
|
2020-02-29 08:15:12 +00:00
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Ah ah ah, you didn't say the magic word"`)
|
|
|
|
w.WriteHeader(401)
|
|
|
|
w.Write([]byte("401 Unauthorized\n"))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|