forked from jfyne/live
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
101 lines (86 loc) · 2.12 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
90
91
92
93
94
95
96
97
98
99
100
101
package live
import (
"encoding/gob"
"net/http"
"github.com/gorilla/sessions"
"github.com/rs/xid"
)
// sessionID the key to access the live session ID.
const sessionID string = "_lsid"
// sessionCookie the name of the session cookie.
const sessionCookie string = "_ls"
// SessionStore handles storing and retrieving sessions.
type SessionStore interface {
Get(*http.Request) (Session, error)
Save(http.ResponseWriter, *http.Request, Session) error
}
// Session persisted over page loads.
type Session map[string]interface{}
// NewSession create a new session.
func NewSession() Session {
return map[string]interface{}{
sessionID: NewID(),
}
}
// SessionID helper to get the sessions live ID.
func SessionID(session Session) string {
ID, ok := session[sessionID].(string)
if !ok {
return ""
}
return ID
}
// NewID returns a new ID.
func NewID() string {
return xid.New().String()
}
func init() {
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[sessionCookie]
if !ok {
// Create new connection.
ns := NewSession()
sess = ns
} else {
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[sessionCookie] = session
return s.Save(r, w)
}