-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
93 lines (85 loc) · 2.05 KB
/
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
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
package midddleware
import (
"context"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/hayuzi/blogserver/internal/model"
"github.com/hayuzi/blogserver/pkg/app"
"github.com/hayuzi/blogserver/pkg/consts"
"github.com/hayuzi/blogserver/pkg/errcode"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
ecode := errcode.Success
token := ""
if s, ok := c.GetQuery("token"); ok {
token = s
} else {
token = c.GetHeader("token")
}
if token == "" {
ecode = errcode.InvalidParams
} else {
_, err := app.ParseToken(token)
if err != nil {
ecode = errcode.UnauthorizedTokenError
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errcode.UnauthorizedTokenTimeout
default:
ecode = errcode.UnauthorizedTokenError
}
}
}
if ecode != errcode.Success {
response := app.NewResponse(c)
response.ToResponseError(ecode)
c.Abort()
return
}
c.Next()
}
}
func JWTAdmin() gin.HandlerFunc {
return func(c *gin.Context) {
ecode := errcode.Success
token := ""
if s, ok := c.GetQuery("token"); ok {
token = s
} else {
token = c.GetHeader("token")
}
if token == "" {
ecode = errcode.InvalidParams
} else {
claims, err := app.ParseToken(token)
if err != nil {
ecode = errcode.UnauthorizedTokenError
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errcode.UnauthorizedTokenTimeout
default:
ecode = errcode.UnauthorizedTokenError
}
} else if claims.UserType != model.UserTypeAdmin {
ecode = errcode.UnauthorizedUserNotAdmin
}
}
if ecode != errcode.Success {
response := app.NewResponse(c)
response.ToResponseError(ecode)
c.Abort()
return
}
c.Next()
}
}
func JWTInjectClaims() gin.HandlerFunc {
return func(c *gin.Context) {
claims, _ := app.GetJwtClaims(c)
ctx := context.WithValue(c.Request.Context(), consts.ContextLoginUserKey, claims)
c.Request = c.Request.WithContext(ctx)
c.Set(consts.ContextLoginUserKey, claims)
c.Next()
}
}