-
Notifications
You must be signed in to change notification settings - Fork 43
/
cookie.go
78 lines (67 loc) · 1.84 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
package identity
import (
"crypto/rand"
"encoding/base64"
webhttp "github.com/yoyofx/yoyogo/web/context"
"io"
"net/http"
"strconv"
"time"
)
// Cookie cookie provider for identity store
type Cookie struct {
sessionCookieName string
httpContext *webhttp.HttpContext
mMaxLifeTime int64
}
var defaultLifeTime int64 = 3600
//NewCookie new cookie provider
func NewCookie() *Cookie {
return &Cookie{
sessionCookieName: "YOYOGO_SESSIONID",
httpContext: nil,
mMaxLifeTime: defaultLifeTime,
}
}
//SetContext set http context
func (c *Cookie) SetContext(cxt interface{}) {
c.httpContext = cxt.(*webhttp.HttpContext)
}
//SetName Set cookie name
func (c *Cookie) SetName(name string) {
c.sessionCookieName = name
}
//SetMaxLifeTime set life time
func (c *Cookie) SetMaxLifeTime(liftTime int64) {
c.mMaxLifeTime = liftTime
}
//SetID set session id
func (c Cookie) SetID(sessionId string) {
cookie := &http.Cookie{Name: c.sessionCookieName, Value: sessionId, Path: "/", HttpOnly: true, MaxAge: int(c.mMaxLifeTime)}
http.SetCookie(c.httpContext.Output.Response, cookie)
}
// GetID get session id
func (c Cookie) GetID() string {
cookie, err := c.httpContext.Input.Request.Cookie(c.sessionCookieName)
if err != nil || cookie.Value == "" {
newSessionId := newId()
c.SetID(newSessionId)
return newSessionId
} else {
return cookie.Value
}
}
// Clear clear all session
func (c Cookie) Clear() {
expiration := time.Now()
cookie := http.Cookie{Name: c.sessionCookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
c.httpContext.Output.Response.Header().Add("Set-Cookie", cookie.String())
}
func newId() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
nano := time.Now().UnixNano() //微秒
return strconv.FormatInt(nano, 10)
}
return base64.URLEncoding.EncodeToString(b)
}