-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcookie.go
344 lines (306 loc) · 7.97 KB
/
cookie.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
Copyright 2016 Wenhui Shen <www.webx.top>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package echo
import (
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/webx-top/codec"
"github.com/webx-top/com"
"github.com/webx-top/echo/param"
)
var (
DefaultCookieOptions = &CookieOptions{
Path: `/`,
Cryptor: NewCookieCryptor(codec.Default, com.RandomString(16)),
}
)
// CookieOptions cookie options
type CookieOptions struct {
Prefix string
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
// MaxAge>0 means Max-Age attribute present and given in seconds.
MaxAge int
// Expires
Expires time.Time
Path string
Domain string
Secure bool
HttpOnly bool
SameSite string // strict / lax
Cryptor CookieCryptor
}
type CookieCryptor interface {
EncryptString(input string) (string, error)
DecryptString(input string) (string, error)
}
type Codec interface {
Encode(rawData, authKey string) string
Decode(cryptedData, authKey string) string
}
func NewCookieCryptor(codec Codec, secret string) CookieCryptor {
return cookieCodec{secret: secret, codec: codec}
}
type cookieCodec struct {
secret string
codec Codec
}
func (c cookieCodec) EncryptString(input string) (string, error) {
return c.codec.Encode(input, c.secret), nil
}
func (c cookieCodec) DecryptString(input string) (string, error) {
return c.codec.Decode(input, c.secret), nil
}
func (c *CookieOptions) Clone() *CookieOptions {
clone := *c
return &clone
}
func (c *CookieOptions) SetMaxAge(maxAge int) *CookieOptions {
c.MaxAge = maxAge
c.Expires = param.EmptyTime
return c
}
func (c *CookieOptions) EncryptString(input string) (string, error) {
if c.Cryptor == nil {
return input, nil
}
return c.Cryptor.EncryptString(input)
}
func (c *CookieOptions) DecryptString(input string) (string, error) {
if c.Cryptor == nil {
return input, nil
}
return c.Cryptor.DecryptString(input)
}
// Cookier interface
type Cookier interface {
Get(key string) string
DecryptGet(key string) string
Add(cookies ...*http.Cookie) Cookier
Set(key string, val string, args ...interface{}) Cookier
EncryptSet(key string, val string, args ...interface{}) Cookier
Send()
}
// NewCookier create a cookie instance
func NewCookier(ctx Context) Cookier {
return &cookie{
context: ctx,
cookies: []*http.Cookie{},
indexes: map[string]int{},
}
}
type cookie struct {
context Context
cookies []*http.Cookie
indexes map[string]int
lock sync.RWMutex
}
func (c *cookie) Send() {
c.lock.RLock()
for _, cookie := range c.cookies {
c.context.Response().SetCookie(cookie)
}
c.lock.RUnlock()
}
func (c *cookie) record(stdCookie *http.Cookie) {
c.lock.Lock()
if idx, ok := c.indexes[stdCookie.Name]; ok {
c.cookies[idx] = stdCookie
c.lock.Unlock()
return
}
c.indexes[stdCookie.Name] = len(c.cookies)
c.cookies = append(c.cookies, stdCookie)
c.lock.Unlock()
}
func (c *cookie) Get(key string) string {
var val string
if v := c.context.Request().Cookie(c.context.CookieOptions().Prefix + key); len(v) > 0 {
val, _ = url.QueryUnescape(v)
}
return val
}
func (c *cookie) DecryptGet(key string) string {
val := c.Get(key)
if len(val) == 0 || c.context.CookieOptions().Cryptor == nil {
return val
}
val = com.URLSafeBase64(val, false)
decrypted, err := c.context.CookieOptions().Cryptor.DecryptString(val)
if err == nil {
val = decrypted
} else {
c.context.Logger().Warnf(`%v: %s`, err, val)
val = ``
}
return val
}
func (c *cookie) Add(cookies ...*http.Cookie) Cookier {
c.lock.Lock()
for _, cookie := range c.cookies {
if idx, ok := c.indexes[cookie.Name]; ok {
c.cookies[idx] = cookie
continue
}
c.indexes[cookie.Name] = len(c.cookies)
c.cookies = append(c.cookies, cookie)
}
c.lock.Unlock()
return c
}
// Set Set cookie value
// @param string key
// @param string value
// @param int|int64|time.Duration args[0]:maxAge (seconds)
// @param string args[1]:path (/)
// @param string args[2]:domain
// @param bool args[3]:secure
// @param bool args[4]:httpOnly
// @param string args[5]:sameSite (lax/strict/default)
func (c *cookie) Set(key string, val string, args ...interface{}) Cookier {
cookie := NewCookie(key, val, c.context.CookieOptions())
switch len(args) {
case 6:
sameSite, _ := args[5].(string)
CookieSameSite(cookie, sameSite)
fallthrough
case 5:
httpOnly, _ := args[4].(bool)
cookie.HttpOnly = httpOnly
fallthrough
case 4:
secure, _ := args[3].(bool)
cookie.Secure = secure
fallthrough
case 3:
domain, _ := args[2].(string)
cookie.Domain = domain
fallthrough
case 2:
ppath, _ := args[1].(string)
if len(ppath) == 0 {
ppath = `/`
}
cookie.Path = ppath
fallthrough
case 1:
switch v := args[0].(type) {
case *http.Cookie:
CopyCookieOptions(v, cookie)
case *CookieOptions:
cookie.MaxAge = v.MaxAge
cookie.Expires = v.Expires
if len(v.Path) == 0 {
v.Path = `/`
}
cookie.Path = v.Path
cookie.Domain = v.Domain
cookie.Secure = v.Secure
cookie.HttpOnly = v.HttpOnly
CookieSameSite(cookie, v.SameSite)
case int:
CookieMaxAge(cookie, v)
case int64:
CookieMaxAge(cookie, int(v))
case time.Duration:
CookieMaxAge(cookie, int(v.Seconds()))
case time.Time:
CookieExpires(cookie, v)
}
}
c.record(cookie)
return c
}
func (c *cookie) EncryptSet(key string, val string, args ...interface{}) Cookier {
if len(val) > 0 && c.context.CookieOptions().Cryptor != nil {
encrypted, err := c.context.CookieOptions().Cryptor.EncryptString(val)
if err == nil {
val = com.URLSafeBase64(encrypted, true)
} else {
c.context.Logger().Warnf(`%v: %s`, err, val)
return c
}
}
return c.Set(key, val, args...)
}
// CookieMaxAge 设置有效时长(秒)
// IE6/7/8不支持
// 如果同时设置了MaxAge和Expires,则优先使用MaxAge
// 设置MaxAge则代表每次保存Cookie都会续期,因为MaxAge是基于保存时间来设置的
func CookieMaxAge(stdCookie *http.Cookie, p int) {
stdCookie.MaxAge = p
if p > 0 {
stdCookie.Expires = time.Unix(time.Now().Unix()+int64(p), 0)
} else if p < 0 {
stdCookie.Expires = time.Unix(1, 0)
} else {
stdCookie.Expires = param.EmptyTime
}
}
// CookieExpires 设置过期时间
// 所有浏览器都支持
// 如果仅仅设置Expires,因为过期时间是固定的,所以不会导致保存Cookie时被续期
func CookieExpires(stdCookie *http.Cookie, expires time.Time) {
if expires.IsZero() {
return
}
stdCookie.MaxAge = 0
stdCookie.Expires = expires
}
// CookieSameSite 设置SameSite
func CookieSameSite(stdCookie *http.Cookie, p string) {
switch strings.ToLower(p) {
case `lax`:
stdCookie.SameSite = http.SameSiteLaxMode
case `strict`:
stdCookie.SameSite = http.SameSiteStrictMode
default:
stdCookie.SameSite = http.SameSiteDefaultMode
}
}
// CopyCookieOptions copy cookie options
func CopyCookieOptions(from *http.Cookie, to *http.Cookie) {
to.MaxAge = from.MaxAge
to.Expires = from.Expires
if len(from.Path) == 0 {
from.Path = `/`
}
to.Path = from.Path
to.Domain = from.Domain
to.Secure = from.Secure
to.HttpOnly = from.HttpOnly
to.SameSite = from.SameSite
}
// NewCookie 新建cookie对象
func NewCookie(key, value string, opt *CookieOptions) *http.Cookie {
c := &http.Cookie{
Name: opt.Prefix + key,
Value: value,
Path: `/`,
Domain: opt.Domain,
MaxAge: opt.MaxAge,
Expires: opt.Expires,
Secure: opt.Secure,
HttpOnly: opt.HttpOnly,
}
if len(opt.Path) > 0 {
c.Path = opt.Path
}
if len(opt.SameSite) > 0 {
CookieSameSite(c, opt.SameSite)
}
return c
}