From 526bfd99472cf9dbcda081024b2f4ad5aa7c5ea2 Mon Sep 17 00:00:00 2001 From: Mzack9999 Date: Fri, 19 Feb 2021 20:59:30 +0100 Subject: [PATCH 1/2] refactoring basic auth option --- simplehttpserver.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/simplehttpserver.go b/simplehttpserver.go index e181945..d0314ad 100644 --- a/simplehttpserver.go +++ b/simplehttpserver.go @@ -9,13 +9,15 @@ import ( "net/http" "net/http/httputil" "path" + "strings" ) type options struct { ListenAddress string Folder string - Username string - Password string + BasicAuth string + username string + password string Realm string Certificate string Key string @@ -34,8 +36,7 @@ func main() { flag.StringVar(&opts.Certificate, "cert", "", "Certificate") flag.StringVar(&opts.Key, "key", "", "Key") flag.BoolVar(&opts.Verbose, "v", false, "Verbose") - flag.StringVar(&opts.Username, "username", "", "Basic auth username") - flag.StringVar(&opts.Password, "password", "", "Basic auth password") + flag.StringVar(&opts.BasicAuth, "basic-auth", "", "Basic auth (username:password)") flag.StringVar(&opts.Realm, "realm", "Please enter username and password", "Realm") flag.Parse() @@ -46,7 +47,14 @@ func main() { log.Printf("Serving %s on http://%s/...", opts.Folder, opts.ListenAddress) layers := loglayer(http.FileServer(http.Dir(opts.Folder))) - if opts.Username != "" || opts.Password != "" { + if opts.BasicAuth != "" { + baTokens := strings.SplitN(opts.BasicAuth, ":", 1) + if len(baTokens) > 0 { + opts.username = baTokens[0] + } + if len(baTokens) > 1 { + opts.password = baTokens[1] + } layers = loglayer(basicauthlayer(http.FileServer(http.Dir(opts.Folder)))) } @@ -94,7 +102,7 @@ func loglayer(handler http.Handler) http.Handler { func basicauthlayer(handler http.Handler) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() - if !ok || user != opts.Username || pass != opts.Password { + if !ok || user != opts.username || pass != opts.password { w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", opts.Realm)) w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("Unauthorized.\n")) //nolint From 1593493b6a65f6ca659dcfa69fc6235fa203f07e Mon Sep 17 00:00:00 2001 From: Mzack9999 Date: Tue, 23 Feb 2021 01:35:25 +0100 Subject: [PATCH 2/2] fixing split amount --- simplehttpserver.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/simplehttpserver.go b/simplehttpserver.go index d0314ad..809e52c 100644 --- a/simplehttpserver.go +++ b/simplehttpserver.go @@ -48,7 +48,7 @@ func main() { log.Printf("Serving %s on http://%s/...", opts.Folder, opts.ListenAddress) layers := loglayer(http.FileServer(http.Dir(opts.Folder))) if opts.BasicAuth != "" { - baTokens := strings.SplitN(opts.BasicAuth, ":", 1) + baTokens := strings.SplitN(opts.BasicAuth, ":", 2) if len(baTokens) > 0 { opts.username = baTokens[0] }