-
Notifications
You must be signed in to change notification settings - Fork 27
/
session.go
89 lines (76 loc) · 1.82 KB
/
session.go
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
package live
import (
"encoding/gob"
"net/http"
"github.com/gorilla/sessions"
"github.com/rs/xid"
)
// SessionStore handles storing and retrieving sessions.
type SessionStore interface {
Get(*http.Request) (Session, error)
Save(http.ResponseWriter, *http.Request, Session) error
}
// Session what we will actually store across page loads.
type Session struct {
ID string
}
// NewSession create a new session.
func NewSession() Session {
return Session{ID: NewID()}
}
// ValueKey type for session keys.
type ValueKey string
// NewID returns a new ID.
func NewID() string {
return xid.New().String()
}
func init() {
gob.Register(ValueKey(""))
gob.Register(Session{})
}
// CookieStore a `gorilla/sessions` based cookie store.
type CookieStore struct {
Store *sessions.CookieStore
sessionName string // session name.
}
// NewCookieStore create a new `gorilla/sessions` based cookie store.
func NewCookieStore(sessionName string, keyPairs ...[]byte) *CookieStore {
s := sessions.NewCookieStore(keyPairs...)
s.Options.HttpOnly = true
s.Options.Secure = false
s.Options.SameSite = http.SameSiteStrictMode
return &CookieStore{
Store: s,
sessionName: sessionName,
}
}
// Get get a session.
func (c CookieStore) Get(r *http.Request) (Session, error) {
var sess Session
session, err := c.Store.Get(r, c.sessionName)
if err != nil {
return NewSession(), err
}
vals, ok := session.Values["s"]
if !ok {
// Create new connection.
ns := NewSession()
sess = ns
}
sess, ok = vals.(Session)
if !ok {
// Create new session and set.
ns := NewSession()
sess = ns
}
return sess, nil
}
// Save a session.
func (c CookieStore) Save(w http.ResponseWriter, r *http.Request, session Session) error {
s, err := c.Store.Get(r, c.sessionName)
if err != nil {
return err
}
s.Values["s"] = session
return s.Save(r, w)
}