From f7098bd3827274e2ba6a69fa308ef9b815c8eb48 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Thu, 18 May 2023 16:30:23 -0600 Subject: [PATCH] Adding sessions package though it's not useful yet --- server/server.go | 2 ++ sessions/middleware.go | 40 ++++++++++++++++++++++++++++++++++++++++ sessions/sessions.go | 4 ++++ 3 files changed, 46 insertions(+) create mode 100644 sessions/middleware.go create mode 100644 sessions/sessions.go diff --git a/server/server.go b/server/server.go index bd38e72..a100cd2 100644 --- a/server/server.go +++ b/server/server.go @@ -34,6 +34,7 @@ import ( "hg.code.netlandish.com/~netlandish/gobwebs/config" "hg.code.netlandish.com/~netlandish/gobwebs/email" "hg.code.netlandish.com/~netlandish/gobwebs/internal/localizer" + "hg.code.netlandish.com/~netlandish/gobwebs/sessions" "hg.code.netlandish.com/~netlandish/gobwebs/storage" "hg.code.netlandish.com/~netlandish/gobwebs/validate" "petersanchez.com/carrier" @@ -537,6 +538,7 @@ func (s *Server) DefaultMiddlewareWithConfig(conf *MiddlewareConfig) *Server { if conf.Sessions { s.e.Use(session.LoadAndSave(s.Session)) // Must be first + s.e.Use(sessions.Middleware(s.Session)) } if conf.ServerContext { s.e.Use(Middleware(s)) diff --git a/sessions/middleware.go b/sessions/middleware.go new file mode 100644 index 0000000..68700ef --- /dev/null +++ b/sessions/middleware.go @@ -0,0 +1,40 @@ +package sessions + +import ( + "context" + "errors" + + "github.com/alexedwards/scs/v2" + "github.com/labstack/echo/v4" +) + +var sessionCtxKey = &contextKey{"session"} + +type contextKey struct { + name string +} + +// Context adds session manager object to context for immediate use +func Context(ctx context.Context, session *scs.SessionManager) context.Context { + return context.WithValue(ctx, sessionCtxKey, session) +} + +// ForContext pulls session manager value for context +func ForContext(ctx context.Context) *scs.SessionManager { + session, ok := ctx.Value(sessionCtxKey).(*scs.SessionManager) + if !ok { + panic(errors.New("invalid session context")) + } + return session +} + +// Middleware will add the provided *scs.SessionManager instance to the context +func Middleware(session *scs.SessionManager) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + ctx := Context(c.Request().Context(), session) + c.SetRequest(c.Request().WithContext(ctx)) + return next(c) + } + } +} diff --git a/sessions/sessions.go b/sessions/sessions.go new file mode 100644 index 0000000..7e8256a --- /dev/null +++ b/sessions/sessions.go @@ -0,0 +1,4 @@ +// Package sessions implements a gobwebs Session interface +// +// This is a TODO still. For now it's a holder for session related middleware +package sessions -- 2.45.2