jwt.go
1.8 KB
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
package middleware
import (
"github.com/beego/beego/v2/server/web/context"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/api/authlib"
"net/http"
"strings"
"time"
)
func JwtFilter() func(ctx *context.Context) {
authLib := authlib.NewApiAuthLib(constant.AUTH_SERVER_HOST)
authLib.BaseServiceGateway.ConnectTimeout = 200 * time.Millisecond
authLib.BaseServiceGateway.ReadWriteTimeout = 200 * time.Millisecond
return func(ctx *context.Context) {
//token := ctx.Request.Header.Get("Authorization")
token := ctx.Request.Header.Get("x-mmm-accesstoken")
if len(token) > 0 {
token = strings.TrimPrefix(token, "Bearer ")
userToken := &domain.UserToken{}
err := userToken.ParseToken(token)
if err != nil {
ctx.Output.SetStatus(http.StatusOK)
ctx.Output.JSON(WithCodeMsgResponse(domain.InvalidRefreshToken), false, false)
return
}
if userToken.UserId > 0 && userToken.CompanyId > 0 {
loginCheckResponse, _ := authLib.LoginCheck(authlib.RequestLoginCheck{Token: token})
if loginCheckResponse != nil && loginCheckResponse.Code == 901 {
ctx.Output.SetStatus(http.StatusOK)
ctx.Output.JSON(WithCodeMsgResponse(domain.InvalidRefreshToken), false, false)
return
}
}
ctx.Input.SetData("UserToken", userToken)
ctx.Input.SetData("Accesstoken", token)
}
}
}
func WithCodeMsgResponse(code int) map[string]interface{} {
msg := "token 过期或无效,需刷新令牌"
if codeMsg, ok := domain.CodeMsg[code]; ok {
msg = codeMsg
}
return map[string]interface{}{
"msg": msg,
"code": code,
"data": struct{}{},
}
}