From 5ba62c56b2a94b9f5ae06b150713f84d5a3144fa Mon Sep 17 00:00:00 2001 From: "kali kaneko (leap communications)" Date: Tue, 11 Aug 2020 22:38:13 +0200 Subject: [refactor] simplify, make port optional --- pkg/backend/webapi.go | 47 ++++++++++++++++++----------------------------- 1 file changed, 18 insertions(+), 29 deletions(-) (limited to 'pkg/backend/webapi.go') diff --git a/pkg/backend/webapi.go b/pkg/backend/webapi.go index a8844e8..568980d 100644 --- a/pkg/backend/webapi.go +++ b/pkg/backend/webapi.go @@ -5,31 +5,20 @@ import ( "log" "net/http" "os" + "strconv" "0xacab.org/leap/bitmask-vpn/pkg/bitmask" ) -func Adapt(h http.Handler, adapters ...Adapter) http.Handler { - for _, adapter := range adapters { - h = adapter(h) - } - return h -} - -type Adapter func(http.Handler) http.Handler - -func CheckAuth(token string) Adapter { - return func(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - t := r.Header.Get("X-Auth-Token") - if t == token { - h.ServeHTTP(w, r) - } else { - w.WriteHeader(http.StatusUnauthorized) - w.Write([]byte("401 - Unauthorized")) - } - - }) +func CheckAuth(handler http.HandlerFunc, token string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + t := r.Header.Get("X-Auth-Token") + if t == token { + handler(w, r) + } else { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("401 - Unauthorized")) + } } } @@ -44,7 +33,6 @@ func webOff(w http.ResponseWriter, r *http.Request) { } func webStatus(w http.ResponseWriter, r *http.Request) { - log.Println("Web UI: status") fmt.Fprintf(w, ctx.Status.String()) } @@ -54,12 +42,13 @@ func webQuit(w http.ResponseWriter, r *http.Request) { os.Exit(0) } -func enableWebAPI() { +func enableWebAPI(port int) { + log.Println("Starting WebAPI in port", port) bitmask.GenerateAuthToken() - auth := CheckAuth(bitmask.ReadAuthToken()) - http.Handle("/vpn/start", Adapt(http.HandlerFunc(webOn), auth)) - http.Handle("/vpn/stop", Adapt(http.HandlerFunc(webOff), auth)) - http.Handle("/vpn/status", Adapt(http.HandlerFunc(webStatus), auth)) - http.Handle("/vpn/quit", Adapt(http.HandlerFunc(webQuit), auth)) - http.ListenAndServe(":8080", nil) + token := bitmask.ReadAuthToken() + http.Handle("/vpn/start", CheckAuth(http.HandlerFunc(webOn), token)) + http.Handle("/vpn/stop", CheckAuth(http.HandlerFunc(webOff), token)) + http.Handle("/vpn/status", CheckAuth(http.HandlerFunc(webStatus), token)) + http.Handle("/vpn/quit", CheckAuth(http.HandlerFunc(webQuit), token)) + http.ListenAndServe(":"+strconv.Itoa(port), nil) } -- cgit v1.2.3