From 2b4eead6805c217a8ab50e49a304ac2cebc30824 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fj=C3=A4llstr=C3=B6m?= Date: Wed, 2 Oct 2024 06:55:26 +0200 Subject: [PATCH] Add database pointer to context. This allow all middlewares to query the database. For alternative authorizations that need to create and read the database. --- main.go | 2 +- router/router.go | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 1125746..8e64ccc 100644 --- a/main.go +++ b/main.go @@ -206,7 +206,7 @@ func main() { } // register routes - app := router.New(tmplDir, extraData, util.SessionSecret) + app := router.New(tmplDir, extraData, util.SessionSecret, db) app.GET(util.BasePath, handler.WireGuardClients(db), handler.ValidSession, handler.RefreshSession) diff --git a/router/router.go b/router/router.go index 59d352e..8e97c79 100644 --- a/router/router.go +++ b/router/router.go @@ -13,6 +13,7 @@ import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/labstack/gommon/log" + "github.com/ngoduykhanh/wireguard-ui/store/jsondb" "github.com/ngoduykhanh/wireguard-ui/util" ) @@ -48,7 +49,7 @@ func (t *TemplateRegistry) Render(w io.Writer, name string, data interface{}, c } // New function -func New(tmplDir fs.FS, extraData map[string]interface{}, secret [64]byte) *echo.Echo { +func New(tmplDir fs.FS, extraData map[string]interface{}, secret [64]byte, db *jsondb.JsonDB) *echo.Echo { e := echo.New() cookiePath := util.GetCookiePath() @@ -60,6 +61,14 @@ func New(tmplDir fs.FS, extraData map[string]interface{}, secret [64]byte) *echo e.Use(session.Middleware(cookieStore)) + // Add db to context so middlewares can use it. + e.Use(func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + c.Set("db", db) + return next(c) + } + }) + // read html template file to string tmplBaseString, err := util.StringFromEmbedFile(tmplDir, "base.html") if err != nil {