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