-
Notifications
You must be signed in to change notification settings - Fork 5
/
gin-jwt-session.go
387 lines (349 loc) · 11.5 KB
/
gin-jwt-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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package session
import (
"errors"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/gin-gonic/gin"
gorillaContext "github.com/gorilla/context"
"github.com/gorilla/sessions"
"sync"
"time"
)
const defaultShortName = "default"
var (
once sync.Once
//SecretKey to encrypt session
//please clear the browser buffer(ctrl+shift+delete) in case you change the key and token name to new one
SecretKey = "welcome to Scott Huang's Session and JWT util, please change to your secret accodingly."
//JwtTokenName is JWT token name, also is the JWT session name too
//Not too long and also do not include blank, such as do not set as "a blank name"
JwtTokenName = "jwtTokenSession"
//DefaultFlashSessionName to store the flash session
//Not too long and also do not include blank, such as do not set as "a blank name"
DefaultFlashSessionName = "myDefaultFlashSessionName"
//DefaultSessionName to store other session message
//Not too long and also do not include blank, such as do not set as "a blank name"
DefaultSessionName = "myDefaultSessionName"
//DefaultOption to provide default option
//Maxage set the session duration by second
DefaultOption = &sessions.Options{
Path: "/",
MaxAge: 3600 * 1, //1 hour
HttpOnly: true,
}
//store for the app sessions
store *sessions.CookieStore
)
func init() {
//TODO
}
//ClearMiddleware clear mem to avoid leak.
//you should add this middleware at your main gin.router
//
// Please see note from http://www.gorillatoolkit.org/pkg/sessions
// Important Note: If you aren't using gorilla/mux,
// you need to wrap your handlers with context.ClearHandler as or else you will leak memory!
// ClearHandler actually invoke Clear func
func ClearMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
defer gorillaContext.Clear(c.Request)
c.Next()
}
}
//NewStore only create one session store globally
//The main program need call sessions.NewStore() to initialize store
//User also can set sessions var before call this function to adjust some default parameters
//
//Usage Sample:
// //in your main(), setup session after r = gin.Default()
// sessions.JwtTokenName = "YourJWTTokenName" //string without blank
// sessions.DefaultSessionName = "YourDefaultSessionName" //string without blank
// sessions.DefaultFlashSessionName = "YourDefaultFlashSessionName" //string without blank
// sessions.SecretKey = "Your Secerect Key (*&%(&*%$" //string with any
// sessions.NewStore() //setup the session store
// r.Use(sessions.ClearMiddleware()) //important to avoid memory leak
// //end setup session
func NewStore() {
once.Do(newStore)
}
//internal only
func newStore() {
store = sessions.NewCookieStore([]byte(SecretKey))
}
//Message struct contain message you would like to set in session
//usually you just provide Key and Value only
type Message struct {
Key interface{}
Value interface{}
SessionName string
Options *sessions.Options
}
//Flash type to contain new flash and its session
type Flash struct {
Flash interface{}
SessionName string
}
// Options stores configuration for a session or session store.
// Fields are a subset of http.Cookie fields.
type Options = sessions.Options
//SetMessage will set session into gin.Context per gived SesionMessage
//It is the basic function for other set func to leverage
//
//Usage Sample:
// err := sessions.SetMessage(c,
// sessions.Message{
// Key: sessions.JwtTokenName,
// Value: tokenString,
// // SessionName: "",
// // Options: &sessions.Options{
// // Path: "/",
// // MaxAge: 3600 * 1, //1 hour for session. Btw, the token itself have valid period, so, better set it as same
// // HttpOnly: true,
// // },
// })
func SetMessage(c *gin.Context, message Message) (err error) {
if len(message.SessionName) == 0 || message.SessionName == defaultShortName {
message.SessionName = DefaultSessionName
}
session, err := store.Get(c.Request, message.SessionName)
if err != nil {
return
}
if message.Options == nil {
session.Options = DefaultOption
} else {
session.Options = message.Options
}
session.Values[message.Key] = message.Value
err = session.Save(c.Request, c.Writer)
return err
}
//SetSessionFlash set new flash to givied session
func SetSessionFlash(c *gin.Context, flash Flash) (err error) {
if len(flash.SessionName) == 0 || flash.SessionName == defaultShortName {
flash.SessionName = DefaultFlashSessionName
}
session, err := store.Get(c.Request, flash.SessionName)
if err != nil {
return
}
session.AddFlash(flash.Flash, flash.SessionName)
err = session.Save(c.Request, c.Writer)
return err
}
//SetFlash set new flash to default session
func SetFlash(c *gin.Context, flash interface{}) (err error) {
return SetSessionFlash(c, Flash{
Flash: flash,
SessionName: DefaultFlashSessionName,
})
}
//GetSessionFlashes return previously flashes per gived session
func GetSessionFlashes(c *gin.Context, sessionName string) []interface{} {
if len(sessionName) == 0 || sessionName == defaultShortName {
sessionName = DefaultFlashSessionName
}
session, err := store.Get(c.Request, sessionName)
if err != nil {
return nil
}
flashes := session.Flashes(sessionName)
DeleteSession(c, sessionName) //manual delete flash session
return flashes
}
//GetFlashes return previously flashes from default session
func GetFlashes(c *gin.Context) []interface{} {
return GetSessionFlashes(c, DefaultFlashSessionName)
}
//DeleteSession delete a session
//instead of Set, the delete will set MaxAge to -1
func DeleteSession(c *gin.Context, sessionName string) (err error) {
if len(sessionName) == 0 || sessionName == defaultShortName {
sessionName = DefaultSessionName
}
session, err := store.Get(c.Request, sessionName)
if err != nil {
return
}
session.Options = &sessions.Options{
Path: "/",
MaxAge: -1, //it mean delete
HttpOnly: true,
}
// Save it before we write to the response/return from the handler.
err = session.Save(c.Request, c.Writer)
return err
}
//GetSessionValue session value according
//The base get func, other will leverage this func
func GetSessionValue(c *gin.Context, sessionName string, key interface{}) (value interface{}, err error) {
// Get a session. Get() always returns a session, even if empty.
if len(sessionName) == 0 {
sessionName = DefaultSessionName
}
session, err := store.Get(c.Request, sessionName)
if err != nil {
return nil, err
}
value = session.Values[key]
return
}
//DeleteSessionValue try delete the gived session key value
func DeleteSessionValue(c *gin.Context, sessionName string, key interface{}) (err error) {
if len(sessionName) == 0 {
sessionName = DefaultSessionName
}
session, err := store.Get(c.Request, sessionName)
if err != nil {
return err
}
delete(session.Values, key)
return nil
}
//Delete try delete default session key value
func Delete(c *gin.Context, key interface{}) (err error) {
return DeleteSessionValue(c, DefaultSessionName, key)
}
//GetDefaultSessionValue levarage GetSessionValue to get key value
func GetDefaultSessionValue(c *gin.Context, key interface{}) (value interface{}, err error) {
return GetSessionValue(c, DefaultSessionName, key)
}
//GetString levarage Get to get key value and convert to string
func GetString(c *gin.Context, key interface{}) (value string, err error) {
valueInterface, err := GetDefaultSessionValue(c, key)
if err != nil {
return "", err
}
value, ok := valueInterface.(string)
if !ok {
err = errors.New("convert session value to string failed")
}
return value, err
}
//GetTokenString to get tokenString
func GetTokenString(c *gin.Context) (tokenString string, err error) {
valueInterface, err := GetSessionValue(c, JwtTokenName, JwtTokenName)
if err != nil {
tokenString = ""
return tokenString, err
}
tokenString, ok := valueInterface.(string)
if !ok {
err = errors.New("failed get token string")
}
return tokenString, err
}
//SetTokenString into JwtTokenSession
func SetTokenString(c *gin.Context, tokenString string, seconds int) (err error) {
return SetMessage(c, Message{
Key: JwtTokenName,
Value: tokenString,
SessionName: JwtTokenName,
Options: &Options{
Path: "/",
MaxAge: seconds,
HttpOnly: true,
},
})
}
//DeleteTokenSession delete before generate JWT token string
func DeleteTokenSession(c *gin.Context) (err error) {
return DeleteSession(c, JwtTokenName)
}
//DeleteNormalSession will delete DefaultSessionName and DefaultFlashSessionName
func DeleteNormalSession(c *gin.Context) {
DeleteSession(c, DefaultSessionName)
DeleteSession(c, DefaultFlashSessionName)
}
//DeleteAllSession will delete JwtTokenName/DefaultSessionName/DefaultFlashSessionName
//usually used when user logout
func DeleteAllSession(c *gin.Context) {
DeleteSession(c, JwtTokenName)
DeleteNormalSession(c)
}
//GetInt levarage Get to get key value and convert to int
func GetInt(c *gin.Context, key interface{}) (value int, err error) {
valueInterface, err := GetDefaultSessionValue(c, key)
if err != nil {
return 0, err
}
value, ok := valueInterface.(int)
if !ok {
err = errors.New("convert session value to string failed")
}
return value, err
}
//Set set key value by interface
func Set(c *gin.Context, key, value interface{}) (err error) {
return SetMessage(c, Message{
Key: key,
Value: value,
})
}
//GenerateJWTToken per gived username and token duration
//
// Claims example as below, and we only use below top 3 claims
// "iat": 1416797419, //start
// "exp": 1448333419, //end
// "sub": "jrocket@example.com", //username
//
// "iss": "Online JWT Builder",
// "aud": "www.example.com",
// "GivenName": "Johnny",
// "Surname": "Rocket",
// "Email": "jrocket@example.com",
// "Role": [ "Manager", "Project Administrator" ]
//
func GenerateJWTToken(username string, tokenDuration time.Duration) (tokenString string, err error) {
//start generate jwt token
token := jwt.New(jwt.SigningMethodHS256)
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Add(tokenDuration).Unix()
claims["iat"] = time.Now().Unix()
claims["sub"] = username
//claims["email"] = form.Email
token.Claims = claims
tokenString, err = token.SignedString([]byte(SecretKey))
return tokenString, err
}
//ValidateJWTToken valide JWT per headder firstly
//And then try get from session if above failed
//will return valid username in case no err
//username == "" also mean failed
func ValidateJWTToken(c *gin.Context) (username string, err error) {
//get username firstly
username = ""
//then try valid token
tokenString := c.Request.Header.Get("Authorization")
if "" == tokenString {
//Not in header authorization, try get cookie in case header empty
tokenString, err = GetTokenString(c)
if err != nil {
// log.Println("Validate JWT Error: failed get token from session: ", err.Error())
return username, err
}
// log.Println("success get tokenString: ", tokenString)
}
// log.Println("After get cookie")
// Get token from request
c.Request.Header.Set("Authorization", tokenString)
token, err := request.ParseFromRequest(c.Request, request.AuthorizationHeaderExtractor,
func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
if err != nil {
return username, err
}
if !token.Valid {
return username, errors.New("token not valid")
}
// log.Println("Token claims: ", token.Claims)
err = errors.New("failed to fetch username from token")
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if _username, ok := claims["sub"].(string); ok {
err = nil
username = _username
}
}
return username, err
}