From 4668ba9a0be4bf6ef15cf75e1bbacc4765388fc0 Mon Sep 17 00:00:00 2001 From: Ratul Saha Date: Mon, 31 Oct 2022 12:37:28 +0530 Subject: [PATCH] feat(auth): Added token based auth for stats api --- README.md | 7 ++++++- api/v1/client/client.go | 4 ++-- core/status.go | 9 ++++++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7e3429e..49ee3d2 100644 --- a/README.md +++ b/README.md @@ -193,8 +193,13 @@ Wg Gen Web will only access your profile to get email address and your name, no Wg Gen Web integrates a [WireGuard API implementation](https://github.com/jamescun/wg-api) to display client stats. In order to enable the Status API integration, the following settings need to be configured: ``` -# https://github.com/jamescun/wg-api integration, user and password (basic auth) are optional +# https://github.com/jamescun/wg-api integration WG_STATS_API=http://:8182 + +# Optional: Token Auth +WG_STATS_API_TOKEN= + +# Optional: Basic Auth WG_STATS_API_USER= WG_STATS_API_PASS= ``` diff --git a/api/v1/client/client.go b/api/v1/client/client.go index 6edf842..96f831a 100644 --- a/api/v1/client/client.go +++ b/api/v1/client/client.go @@ -1,6 +1,8 @@ package client import ( + "net/http" + "github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" "github.com/skip2/go-qrcode" @@ -8,14 +10,12 @@ import ( "github.com/vx3r/wg-gen-web/core" "github.com/vx3r/wg-gen-web/model" "golang.org/x/oauth2" - "net/http" ) // ApplyRoutes applies router to gin Router func ApplyRoutes(r *gin.RouterGroup) { g := r.Group("/client") { - g.POST("", createClient) g.GET("/:id", readClient) g.PATCH("/:id", updateClient) diff --git a/core/status.go b/core/status.go index ebd0425..5576c82 100644 --- a/core/status.go +++ b/core/status.go @@ -4,7 +4,8 @@ import ( "bytes" "encoding/json" "errors" - "io/ioutil" + "fmt" + "io" "net/http" "os" "sort" @@ -54,7 +55,9 @@ func fetchWireGuardAPI(reqData apiRequest) (*apiResponse, error) { req.Header.Set("Content-Type", "application/json") req.Header.Set("Cache-Control", "no-cache") - if os.Getenv("WG_STATS_API_USER") != "" { + if os.Getenv("WG_STATS_API_TOKEN") != "" { + req.Header.Set("Authorization", fmt.Sprintf("Token %s", os.Getenv("WG_STATS_API_TOKEN"))) + } else if os.Getenv("WG_STATS_API_USER") != "" { req.SetBasicAuth(os.Getenv("WG_STATS_API_USER"), os.Getenv("WG_STATS_API_PASS")) } @@ -67,7 +70,7 @@ func fetchWireGuardAPI(reqData apiRequest) (*apiResponse, error) { defer res.Body.Close() } - body, readErr := ioutil.ReadAll(res.Body) + body, readErr := io.ReadAll(res.Body) if readErr != nil { return nil, readErr }