
Add new CLI parameters to enable protecting the API endpoints with basic auth authentication. Wrap the server endpoints in a new auth middleware that protects it using the provided basic auth credentials (if set). Store the provided basic auth credentials as hashed values to prevent them from being accidentally leaked. Add unit tests to ensure the new functionality works as expected.
32 lines
748 B
Go
32 lines
748 B
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
)
|
|
|
|
type BasicAuthProvider interface {
|
|
Enabled() bool
|
|
DoesBasicAuthMatch(username, password string) bool
|
|
}
|
|
|
|
func BasicAuthMiddleware(handlerFunc http.HandlerFunc, basicAuthProvider BasicAuthProvider) http.HandlerFunc {
|
|
if basicAuthProvider.Enabled() {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if doesBasicAuthMatch(r, basicAuthProvider) {
|
|
handlerFunc.ServeHTTP(w, r)
|
|
} else {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
}
|
|
}
|
|
}
|
|
return handlerFunc
|
|
}
|
|
|
|
func doesBasicAuthMatch(r *http.Request, basicAuthProvider BasicAuthProvider) bool {
|
|
rawUsername, rawPassword, ok := r.BasicAuth()
|
|
if ok {
|
|
return basicAuthProvider.DoesBasicAuthMatch(rawUsername, rawPassword)
|
|
}
|
|
return false
|
|
}
|