From 02842b19179a848b8e2b548eec39a8bb6c9c25f3 Mon Sep 17 00:00:00 2001 From: Antonio Navarro Perez Date: Mon, 11 Oct 2021 18:50:18 +0200 Subject: [PATCH] Simple webDAV auth implementation (#82) --- cmd/distribyted/main.go | 2 +- config/config.go | 2 ++ config/model.go | 4 +++- templates/config_template.yaml | 2 ++ webdav/http.go | 19 +++++++++++++++++-- 5 files changed, 25 insertions(+), 4 deletions(-) diff --git a/cmd/distribyted/main.go b/cmd/distribyted/main.go index e5a2ea0..5f8e221 100644 --- a/cmd/distribyted/main.go +++ b/cmd/distribyted/main.go @@ -161,7 +161,7 @@ func load(configPath string, port, webDAVPort int, fuseAllowOther bool) error { return } - if err := webdav.NewWebDAVServer(cfs, port); err != nil { + if err := webdav.NewWebDAVServer(cfs, port, conf.WebDAV.User, conf.WebDAV.Pass); err != nil { log.Error().Err(err).Msg("error starting webDAV") } } diff --git a/config/config.go b/config/config.go index 9a7f972..f958101 100644 --- a/config/config.go +++ b/config/config.go @@ -20,6 +20,8 @@ func DefaultConfig() *Root { }, WebDAV: &WebDAVGlobal{ Port: 36911, + User: "admin", + Pass: "admin", }, Torrent: &TorrentGlobal{ GlobalCacheSize: 1024, diff --git a/config/model.go b/config/model.go index fbfb5bb..082ee5c 100644 --- a/config/model.go +++ b/config/model.go @@ -17,7 +17,9 @@ type TorrentGlobal struct { } type WebDAVGlobal struct { - Port int `yaml:"port"` + Port int `yaml:"port"` + User string `yaml:"user"` + Pass string `yaml:"pass"` } type HTTPGlobal struct { diff --git a/templates/config_template.yaml b/templates/config_template.yaml index 10422af..d7f2112 100644 --- a/templates/config_template.yaml +++ b/templates/config_template.yaml @@ -7,6 +7,8 @@ http: # WebDAV specific configuration. Remove this to disable WebDAV. webdav: port: 36911 + user: admin + pass: admin # Specific configuration for torrent backend. torrent: diff --git a/webdav/http.go b/webdav/http.go index 95141ed..921db84 100644 --- a/webdav/http.go +++ b/webdav/http.go @@ -8,7 +8,22 @@ import ( "github.com/rs/zerolog/log" ) -func NewWebDAVServer(fs fs.Filesystem, port int) error { +func NewWebDAVServer(fs fs.Filesystem, port int, user, pass string) error { log.Info().Str("host", fmt.Sprintf("0.0.0.0:%d", port)).Msg("starting webDAV server") - return http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), newHandler(fs)) + + srv := newHandler(fs) + + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + username, password, _ := r.BasicAuth() + if username == user && password == pass { + srv.ServeHTTP(w, r) + return + } + + w.Header().Set("WWW-Authenticate", `Basic realm="BASIC WebDAV REALM"`) + w.WriteHeader(401) + w.Write([]byte("401 Unauthorized\n")) + }) + + return http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil) }