-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_gin.go
58 lines (50 loc) · 1.02 KB
/
jwt_gin.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
package middleware
import (
"github.com/dgrijalva/jwt-go"
"github.com/newpurr/easy-go/errcode"
"github.com/newpurr/easy-go/http/extend/ginc"
"github.com/newpurr/easy-go/util"
"github.com/gin-gonic/gin"
)
func GinJWT() gin.HandlerFunc {
return func(c *gin.Context) {
var (
token string
err error
ecode = errcode.Success
)
token = tryToExtractToken(c)
if token == "" {
ecode = errcode.InvalidParams
goto check
}
// todo
_, err = util.ParseToken(token, "")
if err == nil {
c.Next()
return
}
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errcode.UnauthorizedTokenTimeout
default:
ecode = errcode.UnauthorizedTokenError
}
check:
if ecode != errcode.Success {
response := ginc.NewResponse(c)
response.ToErrorResponse(ecode)
c.Abort()
return
}
}
}
func tryToExtractToken(c *gin.Context) string {
var token string
if s, exist := c.GetQuery("token"); exist {
token = s
} else {
token = c.GetHeader("token")
}
return token
}