-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
106 lines (94 loc) · 2.2 KB
/
Copy pathsession.go
File metadata and controls
106 lines (94 loc) · 2.2 KB
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
package sessions
import (
"net/http"
"github.com/gorilla/sessions"
)
var store *sessions.CookieStore
var storeName string
//Session saves an user Session in memcached.
type Session struct {
Value Unique
token string
req *http.Request
rw http.ResponseWriter
}
//Unique needs GetID function and is used as Value in Session struct.
type Unique interface {
GetID() string
}
//InitSession creates a new gorilla CookieStore.
func InitSession(secret, storeN, domain string) {
store = sessions.NewCookieStore([]byte(secret))
store.Options.Domain = domain
storeName = storeN
}
//NewSession returns a new Session using request and response for futher functions.
func NewSession(r *http.Request, w http.ResponseWriter) *Session {
return &Session{
req: r,
rw: w,
}
}
//Save stores token into CookieStore and memcached.
func (s *Session) Save(u Unique, key string) error {
s.token = newToken()
session, err := store.Get(s.req, storeName)
if err != nil {
return err
}
session.Values[key] = s.token
err = setCacheSession(s)
if err != nil {
return err
}
s.Value = u
return session.Save(s.req, s.rw)
}
//Update saves new session value into memcached storage.
func (s *Session) Update(u Unique, key string) error {
session, err := store.Get(s.req, storeName)
if err != nil {
return err
}
var ok bool
s.token, ok = session.Values[key].(string)
if !ok {
return ErrNoSession
}
s.Value = u
return setCacheSession(s)
}
//Get uses CookieStore to get saved token and gets session value from memcached storage.
func (s *Session) Get(key string) error {
session, err := store.Get(s.req, storeName)
if err != nil {
return err
}
var ok bool
s.token, ok = session.Values[key].(string)
if !ok {
return ErrNoSession
}
return getCacheSession(s)
}
//GetID returns value ID.
func (s *Session) GetID(key string) (id string, err error) {
err = s.Get(key)
if err != nil {
id = s.Value.GetID()
}
return
}
//Delete removes token of CookieStore and memcached value.
func (s *Session) Delete(key string) error {
session, err := store.Get(s.req, storeName)
if err != nil {
return err
}
delete(session.Values, key)
err = session.Save(s.req, s.rw)
if err != nil {
return err
}
return deleteCacheSession(s)
}