diff options
author | Alexander Neonxp Kiryukhin <i@neonxp.ru> | 2024-12-09 01:07:15 +0300 |
---|---|---|
committer | Alexander Neonxp Kiryukhin <i@neonxp.ru> | 2024-12-09 01:07:15 +0300 |
commit | 34ccc98a942098faefb5f4211b215ff9ccc7ad0e (patch) | |
tree | 7696ab4d7c8d9fb09c7e2575d482517f68824ae3 /pkg/middleware/state.go |
Начальный
Diffstat (limited to 'pkg/middleware/state.go')
-rw-r--r-- | pkg/middleware/state.go | 58 |
1 files changed, 58 insertions, 0 deletions
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"` +} |