summaryrefslogblamecommitdiff
path: root/pkg/middleware/state.go
blob: c91841158808ef3134cf029dcc59a73a5983e412 (plain) (tree)

























































                                                                                              
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"`
}