aboutsummaryrefslogtreecommitdiff
path: root/src/sessions/middleware.go
blob: 238047ec30e0ae258c89dd4ce842f6ddd20d8528 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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)
	})
}