diff --git a/config.go b/config.go index 26b542a..4f24303 100644 --- a/config.go +++ b/config.go @@ -14,6 +14,11 @@ type Config struct { HTTP struct{ Listen string `yaml:"listen"` } `yaml:"http"` + Auth struct{ + Enabled bool `yaml:"enabled"` + Username string `yaml:"username"` + Password string `yaml:"password"` + } `yaml:"auth"` Checks struct{ HDD checks.HDDConfig `yaml:"hdd"` Load checks.LoadConfig `yaml:"load"` diff --git a/config.yml b/config.yml index 4417851..fd4f1cc 100644 --- a/config.yml +++ b/config.yml @@ -1,6 +1,11 @@ http: listen: ":3003" +auth: + enabled: false + username: test + password: test + checks: hdd: max_percent: 80 diff --git a/main.go b/main.go index 890b932..4860999 100644 --- a/main.go +++ b/main.go @@ -25,9 +25,31 @@ func init() { checkList = append(checkList, checks.HDD{c.Checks.HDD}, checks.Memory{Config: c.Checks.Memory}, checks.Load{Config: c.Checks.Load}, checks.Systemd{Config: c.Checks.Systemd}) } +func auth(fn http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if c.Auth.Enabled { + user, pass, _ := r.BasicAuth() + if !check(user, pass) { + w.Header().Set("WWW-Authenticate", `Basic realm="MY REALM"`) + http.Error(w, "Unauthorized.", 401) + return + } + } + fn(w, r) + } +} + +func check(u, p string) bool { + if u == c.Auth.Username && p == c.Auth.Password { + return true + } + return false +} + + func main() { - http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { + http.HandleFunc("/", auth(func(writer http.ResponseWriter, request *http.Request) { res, gloableRes := checkSystem() if gloableRes == false { writer.WriteHeader(http.StatusInternalServerError) @@ -41,8 +63,8 @@ func main() { t.Execute(writer, map[string]interface{}{"checks":res, "version": version}) //writer.Write([]byte(s)) - }) - http.HandleFunc("/data.json", handler) + })) + http.HandleFunc("/data.json", auth(handler)) err := http.ListenAndServe(c.HTTP.Listen, nil) log.Fatal().Err(err).Msg("Shutdown") }