-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontexts.go
129 lines (109 loc) · 2.25 KB
/
contexts.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
124
125
126
127
128
129
package rabbit
import (
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
const (
DbField = "_rabbit_db"
TzField = "_rabbit_tz"
UserField = "_rabbit_uid" // for session: uid, for context: *User
GroupField = "_rabbit_gid" // for session: gid, for context: *Group
)
// 1. set [*time.Location] to gin context, for cache
// 2. set [timezone string] to session
func InTimezone(c *gin.Context, timezone string) {
tz, err := time.LoadLocation(timezone)
if err != nil {
return
}
// 1
c.Set(TzField, tz)
// 2
session := sessions.Default(c)
session.Set(TzField, timezone)
session.Save()
}
/*
1. try get cache from context
2. try get from session
3. set context cache
*/
func CurrentTimezone(c *gin.Context) *time.Location {
// 1
if cache, exist := c.Get(TzField); exist && cache != nil {
return cache.(*time.Location)
}
// 2
session := sessions.Default(c)
tzKey := session.Get(TzField)
if tzKey == nil {
if user := CurrentUser(c); user != nil {
tzKey = user.Timezone
}
}
var tz *time.Location
defer func() {
// 3
if tz == nil {
tz = time.UTC
}
c.Set(TzField, tz)
}()
if tzKey == nil {
return time.UTC
}
tz, _ = time.LoadLocation(tzKey.(string))
if tz == nil {
return time.UTC
}
return tz
}
/*
1. try get cache from context
2. try get user from token/session
3. set context cache
*/
func CurrentUser(c *gin.Context) *User {
// 1
if cache, exist := c.Get(UserField); exist && cache != nil {
return cache.(*User)
}
// 2
session := sessions.Default(c)
uid := session.Get(UserField)
if uid == nil {
return nil
}
// 3
db := c.MustGet(DbField).(*gorm.DB)
user, err := GetUserByID(db, uid.(uint))
if err != nil {
return nil
}
c.Set(UserField, user)
return user
}
func CurrentGroup(c *gin.Context) *Group {
if cache, exists := c.Get(GroupField); exists && cache != nil {
return cache.(*Group)
}
session := sessions.Default(c)
gid := session.Get(GroupField)
if gid == nil {
return nil
}
db := c.MustGet(DbField).(*gorm.DB)
group, err := GetGroupByID(db, gid.(uint))
if err != nil {
return nil
}
c.Set(GroupField, group)
return group
}
func SwitchGroup(c *gin.Context, gid uint) {
session := sessions.Default(c)
session.Set(GroupField, gid)
session.Save()
}