From 218cd643550ed00d26b6e9772d8a64875b5abf2e Mon Sep 17 00:00:00 2001 From: Alexander Kavon Date: Thu, 30 Nov 2023 01:43:08 -0500 Subject: initial sessions support via sessions pkg, includes session middleware for setting sessions, guest sessions, method to return array of middlewares --- src/sessions/middleware.go | 36 ++++++++++++++++++++++++++++++++++++ src/sessions/sessions.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 src/sessions/middleware.go create mode 100644 src/sessions/sessions.go (limited to 'src/sessions') diff --git a/src/sessions/middleware.go b/src/sessions/middleware.go new file mode 100644 index 0000000..238047e --- /dev/null +++ b/src/sessions/middleware.go @@ -0,0 +1,36 @@ +package sessions + +import ( + "context" + "net/http" +) + +func SetSession(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + scookie, err := r.Cookie("session_token") + if err != nil || scookie.Value == "" { + // no session value or cookie + next.ServeHTTP(w, r) + } + cvalue := scookie.Value + vsession, ok := Sessions[cvalue] + if !ok { + // no session + next.ServeHTTP(w, r) + } + // set session + ctx := context.WithValue(r.Context(), SessionCtxKey("session"), vsession) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func GuestSession(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // if SessionKey does not exist then this is a valid guest request + if _, ok := r.Context().Value(SessionCtxKey("session")).(session); !ok { + next.ServeHTTP(w, r) + } + // else redirect to `/` as this is an auth session + http.Redirect(w, r, "/", http.StatusSeeOther) + }) +} diff --git a/src/sessions/sessions.go b/src/sessions/sessions.go new file mode 100644 index 0000000..d2acab6 --- /dev/null +++ b/src/sessions/sessions.go @@ -0,0 +1,35 @@ +package sessions + +import ( + "net/http" + + "github.com/google/uuid" +) + +type SessionMgr struct { + key string + Values map[string]string +} + +type session map[string]any + +type SessionCtxKey string + +var sessions map[string]session + +func (sm *SessionMgr) NewSession(w http.ResponseWriter, r http.Request) { + token := uuid.NewString() + + // set secure cookie in http.ResponseWriter + // TODO make secure + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: token, + }) + + sessions[token] = session{ + "username": username, + } + // set request context + +} -- cgit v1.2.3