-
Notifications
You must be signed in to change notification settings - Fork 38
/
cookie.go
123 lines (99 loc) · 2.38 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
package auths
import (
"net/http"
"strings"
"time"
"github.com/seal-io/walrus/pkg/dao/types/object"
"github.com/seal-io/walrus/utils/strs"
)
const SessionCookieName = "walrus_session"
func decodeSession(r *http.Request) (subjectID object.ID, domain, value string) {
v := getAccessSession(r)
if v == "" {
return
}
subjectID, domain, value, _ = unwrapAccessSession(v)
return
}
func flushSession(r *http.Request, rw http.ResponseWriter, elements ...string) error {
o, err := r.Cookie(SessionCookieName)
if err != nil {
if len(elements) != 3 {
return nil
}
}
var v string
switch {
case len(elements) == 3:
v, err = wrapAccessSession(object.ID(elements[0]), elements[1], elements[2])
if err != nil {
return err
}
case o != nil:
v = o.Value
}
n := &http.Cookie{
Name: SessionCookieName,
Value: v,
Path: "/",
Domain: "",
Secure: SecureConfig.Get(),
HttpOnly: true,
MaxAge: int(MaxIdleDurationConfig.Get().Round(time.Second) / time.Second),
}
if n.MaxAge > 0 {
n.Expires = time.Now().Add(time.Duration(n.MaxAge) * time.Second)
}
http.SetCookie(rw, n)
return nil
}
func revertSession(r *http.Request, rw http.ResponseWriter) {
_, err := r.Cookie(SessionCookieName)
if err != nil {
return
}
n := &http.Cookie{
Name: SessionCookieName,
Value: "",
Path: "/",
Domain: "",
Secure: SecureConfig.Get(),
HttpOnly: true,
MaxAge: -1,
Expires: time.Now().Add(-time.Second),
}
http.SetCookie(rw, n)
}
func getAccessSession(r *http.Request) string {
c, err := r.Cookie(SessionCookieName)
if err != nil {
return ""
}
return c.Value
}
func unwrapAccessSession(accessSession string) (subjectID object.ID, domain, value string, err error) {
ct, err := strs.DecodeBase64(accessSession)
if err != nil {
return
}
ctbs := strs.ToBytes(&ct)
ptbs, err := EncryptorConfig.Get().Decrypt(ctbs, nil)
if err != nil {
return
}
pt := strs.FromBytes(&ptbs)
if ss := strings.SplitN(pt, ":", 3); len(ss) == 3 {
return object.ID(ss[0]), ss[1], ss[2], nil
}
return "", "", pt, nil
}
func wrapAccessSession(subjectID object.ID, domain, value string) (accessSession string, err error) {
pt := strs.Join(":", string(subjectID), domain, value)
ptbs := strs.ToBytes(&pt)
ctbs, err := EncryptorConfig.Get().Encrypt(ptbs, nil)
if err != nil {
return
}
ct := strs.FromBytes(&ctbs)
return strs.EncodeBase64(ct), nil
}