From 34ccc98a942098faefb5f4211b215ff9ccc7ad0e Mon Sep 17 00:00:00 2001 From: Alexander Neonxp Kiryukhin Date: Mon, 9 Dec 2024 01:07:15 +0300 Subject: Начальный MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/middleware/state.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 pkg/middleware/state.go (limited to 'pkg/middleware/state.go') diff --git a/pkg/middleware/state.go b/pkg/middleware/state.go new file mode 100644 index 0000000..c918411 --- /dev/null +++ b/pkg/middleware/state.go @@ -0,0 +1,58 @@ +package middleware + +import ( + "context" + "encoding/gob" + + "github.com/gorilla/sessions" + "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" +) + +func init() { + gob.Register(&State{}) +} + +func PopulateState() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + sess, err := session.Get("state", c) + if err != nil { + return err + } + + u := sess.Values["state"] + c.Set("state", u) + + ctx := context.WithValue(c.Request().Context(), ContextKey("user"), u) + r := c.Request().WithContext(ctx) + c.SetRequest(r) + + return next(c) + } + } +} + +func SetState(c echo.Context, u State, maxage int) error { + sess, err := session.Get("state", c) + if err != nil { + return err + } + + sess.Values["state"] = u + sess.Options = &sessions.Options{ + Path: "/", + MaxAge: maxage, + HttpOnly: true, + Secure: true, + } + + return sess.Save(c.Request(), c.Response()) +} + +type State struct { + Username string `json:"username"` + CurrentGUID string `json:"current_guid"` + Points int `json:"points"` + Image string `json:"image"` +} -- cgit v1.2.3