-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsession.go
219 lines (181 loc) · 5.08 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// MIT License
// Copyright (c) 2022 Leon Ding
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package gws
import (
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/google/uuid"
)
var (
// Global session storage controller
globalStore Storage
// Global Configure controller
globalConfig *Config
// Session concurrent safe mutex
migrateMux sync.Mutex
ErrSessionNoData = errors.New("session no data")
ErrRemoveSessionFail = errors.New("remove session fail")
ErrMigrateSessionFail = errors.New("migrate session fail")
)
// Values is session item value
type Values map[string]interface{}
// Session is web session struct
type Session struct {
session
}
// session struct
type session struct {
id string
CreateTime time.Time
ExpireTime time.Time
Values
}
// GetSession Get session data from the Request
func GetSession(w http.ResponseWriter, req *http.Request) (*Session, error) {
var session Session
cookie, err := req.Cookie(globalConfig.CookieName)
if cookie == nil || err != nil {
debug.trace(cookie)
return createSession(w, cookie)
}
if len(cookie.Value) >= 73 {
session.id = cookie.Value
if globalStore.Read(&session) != nil {
return createSession(w, cookie)
}
}
debug.trace(&session)
return &session, nil
}
// ID return session id
func (s *Session) ID() string {
return s.id
}
// Sync save data modify
func (s *Session) Sync() error {
debug.trace(s)
return globalStore.Write(s)
}
// Migrate migrate old session data to new session
func Migrate(write http.ResponseWriter, old *Session) (*Session, error) {
var (
ns = NewSession()
cookie = NewCookie()
)
migrateMux.Lock()
ns.Values = old.Values
cookie.Value = ns.id
cookie.MaxAge = int(globalConfig.LifeTime) / 1e9
migrateMux.Unlock()
return ns,
func() error {
if ns.Sync() != nil {
return ErrMigrateSessionFail
}
if globalStore.Remove(old) != nil {
return ErrRemoveSessionFail
}
http.SetCookie(write, cookie)
return nil
}()
}
// createSession return new session
func createSession(w http.ResponseWriter, cookie *http.Cookie) (*Session, error) {
// FIX BUG:
// https://deepsource.io/gh/auula/gws/run/5b13c99b-9101-4e4f-8197-acfd730c28a0/go/SCC-SA4009
session := NewSession()
debug.trace(session)
if cookie == nil {
cookie = NewCookie()
}
cookie.Value = session.id
cookie.MaxAge = int(globalConfig.LifeTime) / 1e9
if err := globalStore.Write(session); err != nil {
return nil, err
}
debug.trace(cookie)
http.SetCookie(w, cookie)
debug.trace(session)
return session, nil
}
// NewCookie return default config cookie pointer
func NewCookie() *http.Cookie {
return &http.Cookie{
Domain: globalConfig.Domain,
Path: globalConfig.Path,
Name: globalConfig.CookieName,
Secure: globalConfig.Secure,
HttpOnly: globalConfig.HttpOnly,
}
}
// uuid73 generate session uuid length 73
func uuid73() string {
return fmt.Sprintf("%s-%s", uuid.New().String(), uuid.New().String())
}
// NewSession return new session
func NewSession() *Session {
nowTime := time.Now()
return &Session{
session: session{
id: uuid73(),
Values: make(Values),
CreateTime: nowTime,
ExpireTime: nowTime.Add(lifeTime),
},
}
}
// Expired check current session whether expire
func (s *Session) Expired() bool {
return time.Duration(s.ExpireTime.UnixNano()) <= time.Duration(time.Now().UnixNano())
}
// Invalidate remove the session
func Invalidate(s *Session) error {
debug.trace(s)
return globalStore.Remove(s)
}
// Malloc reallocation of memory
func Malloc(v *Values) {
*v = make(Values)
}
// Open Initialize storage with custom configuration
func Open(opt Configure) {
debug.trace(opt)
globalConfig = opt.Parse()
switch globalConfig.store {
case ram:
globalStore = NewRAM()
case rds:
rdb := NewRds()
timeout, cancelFunc := timeoutCtx()
defer cancelFunc()
if err := rdb.store.Ping(timeout).Err(); err != nil {
panic(err.Error())
}
globalStore = rdb
default:
globalStore = NewRAM()
}
}
// StoreFactory Initialize custom storage media
func StoreFactory(opt Options, store Storage) {
globalConfig = opt.Parse()
globalStore = store
}