diff options
Diffstat (limited to 'src/sessions')
| -rw-r--r-- | src/sessions/middleware.go | 36 | ||||
| -rw-r--r-- | src/sessions/sessions.go | 35 |
2 files changed, 71 insertions, 0 deletions
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 + +} |
