-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.go
61 lines (52 loc) · 1.32 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
package doorman
import (
"fmt"
"net/http"
"github.com/gorilla/securecookie"
"go.uber.org/zap"
)
const (
cookieName = "doorman"
)
func newRandomKey(n int) []byte {
return securecookie.GenerateRandomKey(n)
}
type cookieData map[string]interface{}
type cookieHandler struct {
*zap.Logger
insecure bool
domain string
c *securecookie.SecureCookie
}
func newCookie(logger *zap.Logger, hash, block []byte, insecure bool, domain string) *cookieHandler {
return &cookieHandler{
Logger: logger,
insecure: insecure,
domain: domain,
c: securecookie.New(hash, block)}
}
func (ch *cookieHandler) set(w http.ResponseWriter, value cookieData) {
if encoded, err := ch.c.Encode(cookieName, value); err == nil {
cookie := &http.Cookie{
Name: cookieName,
Domain: ch.domain,
Value: encoded,
Path: "/",
Secure: !ch.insecure,
HttpOnly: true,
}
http.SetCookie(w, cookie)
} else {
ch.Error("cannot encode cookie", zap.Error(err))
}
}
func (ch *cookieHandler) get(r *http.Request) (cookieData, error) {
if cookie, err := r.Cookie(cookieName); err == nil {
values := make(cookieData)
if err = ch.c.Decode(cookieName, cookie.Value, &values); err == nil {
return values, nil
}
return nil, fmt.Errorf("cookie cannot be decoded")
}
return nil, fmt.Errorf("no cookie found")
}