-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
session.go
99 lines (78 loc) · 1.82 KB
/
session.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
package main
import (
"context"
"encoding/gob"
"fmt"
"github.com/alexedwards/scs/v2"
"github.com/gin-gonic/gin"
"time"
)
func init() {
gob.Register(ProviderOb{})
}
type cfSessionManager struct {
session *scs.SessionManager
}
func (self *cfSessionManager) GetSCSSessionManager() *scs.SessionManager {
return self.session
}
func NewSessionManager(r *gin.Engine) *cfSessionManager {
self := &cfSessionManager{
session: scs.New(),
}
self.session.Lifetime = (24 * 365) * time.Hour
r.Use(self.Sessions())
//db, _ := sql.Open( "sqlite3", "sessions.db" )
//session.Store = sqlite3store.New( db )
return self
}
func (self *cfSessionManager) Sessions() gin.HandlerFunc {
return func(c *gin.Context) {
//fmt.Printf("Sessions")
r := c.Request
token, _ := c.Cookie("session")
ctx, _ := self.session.Load(r.Context(), token)
if ctx == nil {
fmt.Println("no session")
} else {
c.Set("session", ctx)
}
//fmt.Printf("token:%s\n", token )
c.Next()
}
}
func (self *cfSessionManager) GetSession(rCtx *gin.Context) context.Context {
ctx, _ := rCtx.Get("session")
ctx2 := ctx.(context.Context)
return ctx2
}
func (self *cfSessionManager) WriteSession(c *gin.Context) {
sI, _ := c.Get("session")
s := sI.(context.Context)
status := self.session.Status(s)
if status == scs.Unmodified {
return
}
//var cExpires int
var cMaxAge int
var token string
var expiry time.Time
switch status {
case scs.Modified:
token, expiry, _ = self.session.Commit(s)
//fmt.Println("session committed")
//cExpires = time.Unix( expiry.Unix() + 1, 0 )
cMaxAge = int(time.Until(expiry).Seconds() + 1)
case scs.Destroyed:
//cExpires = time.Unix( 1, 0 )
cMaxAge = -1
}
c.SetCookie(
"session",
token,
cMaxAge,
"/",
self.session.Cookie.Domain,
self.session.Cookie.Secure,
self.session.Cookie.HttpOnly)
}