summaryrefslogtreecommitdiff
path: root/middleware/session/session.go
blob: 4d02bf15ef4b4d85a11836e4ddbcd900fb6a46e8 (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
package session

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

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

type Config struct {
	SessionCookie string
	Path          string
	Domain        string
	Secure        bool
	HttpOnly      bool
	MaxAge        int
}

var DefaultConfig Config = Config{
	SessionCookie: "_session",
	Path:          "/",
	Domain:        "",
	Secure:        false,
	HttpOnly:      true,
	MaxAge:        30 * 3600,
}

func Middleware(config Config, storer Store) mux.Middleware {
	if storer == nil {
		storer = &MemoryStore{store: sync.Map{}}
	}

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

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

			ctx := context.WithValue(r.Context(), middleware.SessionValueKey, &values)
			ctx = context.WithValue(ctx, middleware.SessionIDKey, sessionID)
			ctx = context.WithValue(ctx, middleware.SessionConfigKey, config)
			ctx = context.WithValue(ctx, middleware.SessionStorerKey, storer)

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

			storer.Save(r.Context(), sessionID, values)

		})
	}
}

func FromRequest(r *http.Request) *Value {
	return r.Context().Value(middleware.SessionValueKey).(*Value)
}

func Clear(w http.ResponseWriter, r *http.Request) {
	storer := r.Context().Value(middleware.SessionStorerKey).(Store)
	sessionID := r.Context().Value(middleware.SessionIDKey).(string)
	storer.Remove(r.Context(), sessionID)
	config := r.Context().Value(middleware.SessionConfigKey).(Config)
	http.SetCookie(w, &http.Cookie{
		Name:     config.SessionCookie,
		Value:    sessionID,
		Path:     config.Path,
		Domain:   config.Domain,
		Secure:   config.Secure,
		HttpOnly: config.HttpOnly,
		MaxAge:   -1,
	})
}