aboutsummaryrefslogtreecommitdiff
path: root/src/sessions/middleware.go
blob: c1d05282ecf9f9b632a3413844466ebd94f8da45 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
package sessions

import (
	"context"
	"net/http"
)

func SetSession(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// is there a session_token cookie?
		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 := GetSession(cvalue)
		if !ok {
			// no session
			next.ServeHTTP(w, r)
		}
		// set session
		ctx := context.WithValue(r.Context(), SessionCtxKey("session"), vsession.Id())
		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")); !ok {
			next.ServeHTTP(w, r)
		}
		// else redirect to `/u/me` as this is an auth session
		http.Redirect(w, r, "/u/me", http.StatusSeeOther)
	})
}

func AuthSession(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// if session key not exists, then this is a guest session request redirect to login page
		if _, ok := r.Context().Value(SessionCtxKey("session")); !ok {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
		}

		// else this is a valid auth session request
		next.ServeHTTP(w, r)
	})
}