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

import (
	"context"
	"net/http"

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

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

type SessionManager struct {
	SessionID string
	Storer    session.Store
	MaxAge    int
}

func (s *SessionManager) Load(ctx context.Context) session.Value {
	return s.Storer.Load(ctx, s.SessionID)
}

func (s *SessionManager) Save(ctx context.Context, value session.Value) error {
	return s.Storer.Save(ctx, s.SessionID, value)
}

func (s *SessionManager) SetMaxAge(maxAge int) {
	s.MaxAge = maxAge
}

func Session(config *SessionConfig, storer session.Store) Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			sessionID := objectid.New().String()
			cookie, err := r.Cookie(config.SessionCookie)
			if err == nil {
				sessionID = cookie.Value
			}
			sessionManager := &SessionManager{SessionID: sessionID, Storer: storer, MaxAge: config.MaxAge}

			h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), sessionKey, &sessionManager)))

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

func SessionFromRequest(r *http.Request) *SessionManager {
	return r.Context().Value(sessionKey).(*SessionManager)
}