summaryrefslogtreecommitdiff
path: root/middleware/session/session.go
blob: 47fc0fbd71ee3f4dbc5f68b93b38c2ed83ad51a5 (plain) (blame)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package session

import (
	"context"
	"errors"
	"net/http"
	"time"

	"go.neonxp.ru/mux"
	"go.neonxp.ru/objectid"
)

type Config struct {
	SessionCookie string
	Path          string
	Domain        string
	Secure        bool
	HttpOnly      bool
	MaxAge        time.Duration
}

var DefaultConfig Config = Config{
	SessionCookie: "_session",
	Path:          "/",
	Domain:        "",
	Secure:        false,
	HttpOnly:      true,
	MaxAge:        365 * 24 * time.Hour,
}

var (
	ErrSessionNotFound    = errors.New("session not found")
	ErrNoSessionInContext = errors.New("no session in context")
)

type SessionManager struct {
	config *Config
	storer Store
}

func New(storer Store) *SessionManager {
	return NewWithConfig(&DefaultConfig, storer)
}

func NewWithConfig(config *Config, storer Store) *SessionManager {
	return &SessionManager{
		config: config,
		storer: storer,
	}
}

func (s *SessionManager) Middleware() mux.Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			var (
				sessionID string
				values    Values
			)
			cookie, err := r.Cookie(s.config.SessionCookie)
			switch {
			case err == nil:
				sessionID = cookie.Value
				values = s.storer.Load(sessionID)
			case errors.Is(err, http.ErrNoCookie):
				sessionID = objectid.New().String()
			}

			ctx := context.WithValue(r.Context(), sessionManagerKey, s)
			ctx = context.WithValue(ctx, sessionIDKey, sessionID)
			ctx = context.WithValue(ctx, sessionValueKey, values)

			h.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

func (s *SessionManager) Values(ctx context.Context) Values {
	aValue := ctx.Value(sessionValueKey)
	values, ok := aValue.(Values)
	if !ok || values == nil {
		values = Values{}
	}

	return values
}

func (s *SessionManager) Save(w http.ResponseWriter, r *http.Request, values Values) error {
	aSessionID := r.Context().Value(sessionIDKey)
	sessionID, ok := aSessionID.(string)
	if !ok {
		return ErrNoSessionInContext
	}

	http.SetCookie(w, &http.Cookie{
		Name:     s.config.SessionCookie,
		Value:    sessionID,
		Path:     s.config.Path,
		Domain:   s.config.Domain,
		Secure:   s.config.Secure,
		HttpOnly: s.config.HttpOnly,
		MaxAge:   int(s.config.MaxAge.Seconds()),
	})

	return s.storer.Save(sessionID, values)
}
func (s *SessionManager) Clear(w http.ResponseWriter, r *http.Request) error {
	aSessionID := r.Context().Value(sessionIDKey)
	sessionID, ok := aSessionID.(string)
	if !ok {
		return ErrNoSessionInContext
	}

	http.SetCookie(w, &http.Cookie{
		Name:     s.config.SessionCookie,
		Value:    sessionID,
		Path:     s.config.Path,
		Domain:   s.config.Domain,
		Secure:   s.config.Secure,
		HttpOnly: s.config.HttpOnly,
		MaxAge:   -1,
	})

	return s.storer.Remove(sessionID)
}

func FromRequest(r *http.Request) *SessionManager {
	return r.Context().Value(sessionManagerKey).(*SessionManager)
}