aboutsummaryrefslogtreecommitdiff
path: root/src/sessions/middleware.go
diff options
context:
space:
mode:
authorAlexander Kavon <hawk@alexkavon.com>2023-11-30 01:43:08 -0500
committerAlexander Kavon <hawk@alexkavon.com>2023-11-30 01:43:08 -0500
commit218cd643550ed00d26b6e9772d8a64875b5abf2e (patch)
tree36b943ea5f73f290dcd0ed3aeacdb0b83852bc5c /src/sessions/middleware.go
parent59bfd1219d36db6ae7b6833aef4f0c71b7b19b74 (diff)
initial sessions support via sessions pkg, includes session middleware for setting sessions, guest sessions, method to return array of middlewares
Diffstat (limited to 'src/sessions/middleware.go')
-rw-r--r--src/sessions/middleware.go36
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)
+ })
+}