-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.go
97 lines (86 loc) · 2.31 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
package util
import (
"encoding/base64"
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"time"
)
// Cookie Names
const (
UserCookieName = "passport"
SignatureCookieName = "signature"
CookieExpiration = 60 * 60 * 24 * 7 // 1 week
)
// UserCookie the truely info in cookie
type UserCookie struct {
Name string `json:"name"`
Email string `json:"email"`
Expiration int64 `json:"expiration"`
}
// IsExpired return true when cookie expired
func (u *UserCookie) IsExpired() bool {
return u.Expiration < time.Now().Unix()
}
// SetLoginCookies in response
func SetLoginCookies(c *gin.Context, username string,email string) (err error) {
// set user cookie
userCookie := &UserCookie{
Name: username,
Email: email,
Expiration: time.Now().Unix() + CookieExpiration,
}
encodedValue, err := json.Marshal(userCookie)
if err != nil {
return err
}
c.SetCookie(UserCookieName, base64.StdEncoding.EncodeToString(encodedValue), CookieExpiration, "/", "", false, false)
// set signature
sig, err := SignData(encodedValue)
if err != nil {
return err
}
c.SetCookie(SignatureCookieName, base64.StdEncoding.EncodeToString(sig), CookieExpiration, "/", "", false, false)
return err
}
// Logout reset client cookie in response, set max age to 0 actually
// due to Set-Cookie will contain other cookies so DO NOT use header.Del("Set-Cookie")
func Logout(c *gin.Context) {
c.SetCookie(UserCookieName, "", -1, "/", "", false, false)
c.SetCookie(SignatureCookieName, "", -1, "/", "", false, false)
}
// GetUserCookie from request header
func GetUserCookie(c *gin.Context) (u *UserCookie, err error) {
userInfo, err := c.Cookie(UserCookieName)
if err != nil {
return nil, err
}
// base64 decode
decodedUserInfo, err := base64.StdEncoding.DecodeString(userInfo)
if err != nil {
return nil, err
}
// get signature
sig, err := c.Cookie(SignatureCookieName)
if err != nil {
return nil, err
}
decodedSignature, err := base64.StdEncoding.DecodeString(sig)
if err != nil {
return nil, err
}
err = VerifyData(decodedUserInfo, decodedSignature)
if err != nil {
// signature verify failed
return nil, err
}
// decode cookie
u = &UserCookie{}
if err = json.Unmarshal(decodedUserInfo, u); err != nil {
return
}
if u.IsExpired() {
return nil, errors.New("cookie expired")
}
return u, nil
}