Add HTTP Basic Auth
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Kekskurse 2021-11-29 05:53:12 +01:00
parent f84f300488
commit 9df2804eb8
Signed by: kekskurse
GPG Key ID: 728ACCB59341E7E4
3 changed files with 35 additions and 3 deletions

View File

@ -14,6 +14,11 @@ type Config struct {
HTTP struct{ HTTP struct{
Listen string `yaml:"listen"` Listen string `yaml:"listen"`
} `yaml:"http"` } `yaml:"http"`
Auth struct{
Enabled bool `yaml:"enabled"`
Username string `yaml:"username"`
Password string `yaml:"password"`
} `yaml:"auth"`
Checks struct{ Checks struct{
HDD checks.HDDConfig `yaml:"hdd"` HDD checks.HDDConfig `yaml:"hdd"`
Load checks.LoadConfig `yaml:"load"` Load checks.LoadConfig `yaml:"load"`

View File

@ -1,6 +1,11 @@
http: http:
listen: ":3003" listen: ":3003"
auth:
enabled: false
username: test
password: test
checks: checks:
hdd: hdd:
max_percent: 80 max_percent: 80

28
main.go
View File

@ -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}) 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() { func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { http.HandleFunc("/", auth(func(writer http.ResponseWriter, request *http.Request) {
res, gloableRes := checkSystem() res, gloableRes := checkSystem()
if gloableRes == false { if gloableRes == false {
writer.WriteHeader(http.StatusInternalServerError) writer.WriteHeader(http.StatusInternalServerError)
@ -41,8 +63,8 @@ func main() {
t.Execute(writer, map[string]interface{}{"checks":res, "version": version}) t.Execute(writer, map[string]interface{}{"checks":res, "version": version})
//writer.Write([]byte(s)) //writer.Write([]byte(s))
}) }))
http.HandleFunc("/data.json", handler) http.HandleFunc("/data.json", auth(handler))
err := http.ListenAndServe(c.HTTP.Listen, nil) err := http.ListenAndServe(c.HTTP.Listen, nil)
log.Fatal().Err(err).Msg("Shutdown") log.Fatal().Err(err).Msg("Shutdown")
} }