summaryrefslogtreecommitdiff
path: root/session/session.go
blob: 5ffd5cdd0116ef0ed9f8f1950db5d629fc2b2386 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package session

import (
	"context"
	"encoding/gob"
	"log"
	"net/http"
	"os"

	"github.com/gorilla/securecookie"
	"github.com/gorilla/sessions"
)

type sessionContextKey struct{}

const (
	sessionCookie = "sessionKeks"
	dataKey       = "data"
)

func init() {
	gob.Register(sessionData{})
}

type Session struct {
	*sessionData
	s *sessions.Session
}

type sessionData struct {
	UserID        int32
	Authenticated bool
}

func (s *Session) Save(w http.ResponseWriter, r *http.Request) {
	s.s.Values[dataKey] = *s.sessionData
	if err := s.s.Save(r, w); err != nil {
		log.Panic("Storing session: ", err)
	}
}

func (s *Session) MaxAge(maxAge int) {
	s.s.Options.MaxAge = maxAge
}

func (s *Session) Invalidate() {
	s.MaxAge(-1)
	s.Authenticated = false
}

func (s *Session) IsNew() bool {
	return s.s.IsNew
}

// From extracts the `Session` from the `Request`.
func From(r *http.Request) Session {
	s := r.Context().Value(sessionContextKey{}).(*sessions.Session)
	s.Options.HttpOnly = true

	sd, ok := s.Values[dataKey].(sessionData)
	if !ok {
		sd = sessionData{}
	}
	return Session{&sd, s}
}

func Handler() func(next http.Handler) http.Handler {
	var key []byte

	if envKey := os.Getenv("GOSTEN_SECRET"); len(envKey) >= 32 {
		key = []byte(envKey)
	} else {
		key = securecookie.GenerateRandomKey(32)
	}

	sessionStore := sessions.NewCookieStore(key)

	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			session, _ := sessionStore.Get(r, sessionCookie)

			ctx := context.WithValue(r.Context(), sessionContextKey{}, session)
			next.ServeHTTP(w, r.WithContext(ctx))
		}
		return http.HandlerFunc(fn)
	}
}