-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
45 lines (40 loc) · 860 Bytes
/
jwt.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
package middleware
import (
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/mwqnice/oh-admin/pkg/app"
"github.com/mwqnice/oh-admin/pkg/errcode"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var (
token string
ecode = errcode.Success
)
if s, exist := c.GetQuery("token"); exist {
token = s
} else {
token = c.GetHeader("token")
}
if token == "" {
ecode = errcode.InvalidParams
} else {
_, err := app.ParseToken(token)
if err != nil {
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errcode.UnauthorizedTokenTimeout
default:
ecode = errcode.UnauthorizedTokenError
}
}
}
if ecode != errcode.Success {
response := app.NewResponse(c)
response.ToErrorResponse(ecode)
c.Abort()
return
}
c.Next()
}
}