forked from go-chassis/go-chassis
/
session_manager.go
executable file
·250 lines (200 loc) · 5.99 KB
/
session_manager.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package session
import (
"errors"
"fmt"
"math/rand"
"net/http"
"strings"
"time"
"github.com/go-chassis/go-chassis/client/rest"
"github.com/go-chassis/go-chassis/core/common"
"github.com/go-chassis/go-chassis/core/lager"
"context"
cache "github.com/patrickmn/go-cache"
)
// ErrResponseNil used for to represent the error response, when it is nil
var ErrResponseNil = errors.New("can not set session, resp is nil")
// Cache session cache variable
var Cache *cache.Cache
func init() {
Cache = initCache()
cookieMap = make(map[string]string)
}
func initCache() *cache.Cache {
var value *cache.Cache
value = cache.New(3e+10, time.Second*30)
return value
}
var cookieMap map[string]string
// getLBCookie gets cookie from local map
func getLBCookie(key string) string {
return cookieMap[key]
}
// setLBCookie sets cookie to local map
func setLBCookie(key, value string) {
cookieMap[key] = value
}
// GetContextMetadata gets data from context
func GetContextMetadata(ctx context.Context, key string) string {
md, ok := ctx.Value(common.ContextHeaderKey{}).(map[string]string)
if ok {
return md[key]
}
return ""
}
// SetContextMetadata sets data to context
func SetContextMetadata(ctx context.Context, key string, value string) context.Context {
md, ok := ctx.Value(common.ContextHeaderKey{}).(map[string]string)
if !ok {
md = make(map[string]string)
}
if md[key] == value {
return ctx
}
md[key] = value
return context.WithValue(ctx, common.ContextHeaderKey{}, md)
}
//GetSessionFromResp return session uuid in resp if there is
func GetSessionFromResp(cookieKey string, resp *http.Response) string {
for _, c := range resp.Cookies() {
if c.Name == cookieKey {
return c.Value
}
}
return ""
}
// SaveSessionIDFromContext check session id in response ctx and save it to session storage
func SaveSessionIDFromContext(ctx context.Context, ep string, autoTimeout int) context.Context {
timeValue := time.Duration(autoTimeout) * time.Second
sessionIDStr := GetContextMetadata(ctx, common.LBSessionID)
if sessionIDStr != "" {
cookieKey := strings.Split(string(sessionIDStr), "=")
if len(cookieKey) > 1 {
sessionIDStr = cookieKey[1]
}
}
ClearExpired()
var sessBool bool
if sessionIDStr != "" {
_, sessBool = Cache.Get(sessionIDStr)
}
if sessionIDStr != "" && sessBool {
cookie := common.LBSessionID + "=" + sessionIDStr
setLBCookie(common.LBSessionID, cookie)
Save(sessionIDStr, ep, timeValue)
return ctx
}
sessionIDValue := generateCookieSessionID()
cookie := common.LBSessionID + "=" + sessionIDValue
setLBCookie(common.LBSessionID, cookie)
Save(sessionIDValue, ep, timeValue)
return SetContextMetadata(ctx, common.LBSessionID, cookie)
}
//Temporary responsewriter for SetCookie
type cookieResponseWriter http.Header
// Header implements ResponseWriter Header interface
func (c cookieResponseWriter) Header() http.Header {
return http.Header(c)
}
//Write is a dummy function
func (c cookieResponseWriter) Write([]byte) (int, error) {
panic("ERROR")
}
//WriteHeader is a dummy function
func (c cookieResponseWriter) WriteHeader(int) {
panic("ERROR")
}
//setCookie appends cookie with already present cookie with ';' in between
func setCookie(resp *http.Response, value string) {
Resp := rest.Response{Resp: resp}
newCookie := common.LBSessionID + "=" + value
oldCookie := string(Resp.GetCookie(common.LBSessionID))
if oldCookie != "" {
//If cookie is already set, append it with ';'
newCookie = newCookie + ";" + oldCookie
}
c1 := http.Cookie{Name: common.LBSessionID, Value: newCookie}
w := cookieResponseWriter(resp.Header)
http.SetCookie(w, &c1)
}
// SaveSessionIDFromHTTP check session id
func SaveSessionIDFromHTTP(ep string, autoTimeout int, resp *http.Response, req *http.Request) {
if resp == nil {
lager.Logger.Warnf("", ErrResponseNil)
return
}
timeValue := time.Duration(autoTimeout) * time.Second
var sessionIDStr string
if c, err := req.Cookie(common.LBSessionID); err == http.ErrNoCookie {
sessionIDStr = ""
} else {
sessionIDStr = c.Value
}
ClearExpired()
var sessBool bool
if sessionIDStr != "" {
_, sessBool = Cache.Get(sessionIDStr)
}
valueChassisLb := GetSessionFromResp(common.LBSessionID, resp)
//if session is in resp, then just save it
if string(valueChassisLb) != "" {
Save(valueChassisLb, ep, timeValue)
} else if sessionIDStr != "" && sessBool {
setCookie(resp, sessionIDStr)
Save(sessionIDStr, ep, timeValue)
} else {
sessionIDValue := generateCookieSessionID()
setCookie(resp, sessionIDValue)
Save(sessionIDValue, ep, timeValue)
}
}
// generateCookieSessionID generate cookies for session id
func generateCookieSessionID() string {
result := make([]byte, 16)
rand.Seed(time.Now().UTC().UnixNano())
tmp := rand.Int63()
rand.Seed(tmp)
for i := 0; i < 16; i++ {
result[i] = byte(rand.Intn(16))
}
result[6] = (result[6] & 0xF) | (4 << 4)
result[8] = (result[8] | 0x40) & 0x7F
return fmt.Sprintf("%x-%x-%x-%x-%x", result[0:4], result[4:6], result[6:8], result[8:10], result[10:])
}
// DeletingKeySuccessiveFailure deleting key successes and failures
func DeletingKeySuccessiveFailure(resp *http.Response) {
Cache.DeleteExpired()
if resp == nil {
valueChassisLb := getLBCookie(common.LBSessionID)
if string(valueChassisLb) != "" {
cookieKey := strings.Split(string(valueChassisLb), "=")
if len(cookieKey) > 1 {
Delete(cookieKey[1])
setLBCookie(common.LBSessionID, "")
}
}
return
}
valueChassisLb := GetSessionFromResp(common.LBSessionID, resp)
if string(valueChassisLb) != "" {
cookieKey := strings.Split(string(valueChassisLb), "=")
if len(cookieKey) > 1 {
Delete(cookieKey[1])
}
}
}
// GetSessionCookie getting session cookie
func GetSessionCookie(ctx context.Context, resp *http.Response) string {
if ctx != nil {
return GetContextMetadata(ctx, common.LBSessionID)
}
if resp == nil {
lager.Logger.Warnf("", ErrResponseNil)
return ""
}
valueChassisLb := GetSessionFromResp(common.LBSessionID, resp)
if string(valueChassisLb) != "" {
return string(valueChassisLb)
}
return ""
}