middleware.go
2.3 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
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
package middleware
import (
"errors"
"github.com/astaxie/beego/context"
"github.com/tiptok/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/application/cachex"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
"strconv"
"strings"
)
var (
errAuthorization = errors.New("无访问权限")
errAuthorizationExpire = errors.New("权限已过期,请重新登录")
)
func CheckAuthorization(ctx *context.Context) {
var (
msg *protocol.ResponseMessage
)
defer func() {
if msg != nil {
ctx.Output.JSON(msg, false, false)
}
}()
authorization := ctx.Input.Header("Authorization")
if len(authorization) == 0 {
msg = protocol.NewResponseMessage(1, errAuthorization.Error())
return
}
var token string
splitToken := strings.Split(authorization, " ")
if len(splitToken) == 1 {
token = splitToken[0]
} else {
token = splitToken[1]
}
claim, err := common.ParseJWTToken(token)
if err != nil {
msg = protocol.NewResponseMessage(1, errAuthorizationExpire.Error())
return
}
userId, _ := strconv.Atoi(claim.Username)
ctx.Input.SetData("x-mmm-id", userId)
return
}
func CheckRoleAccess(ctx *context.Context, object, method string) {
var (
msg *protocol.ResponseMessage
)
defer func() {
if msg != nil {
ctx.Output.JSON(msg, false, false)
}
}()
userId := ctx.Input.GetData("x-mmm-id")
if userId == nil {
msg = protocol.NewResponseMessage(1, errAuthorization.Error())
return
}
validUserRole := cachex.CacheService{}
if ok, _ := validUserRole.ValidUserAccess(int64(userId.(int)), object, method); !ok {
msg = protocol.NewResponseMessage(1, errAuthorization.Error())
return
}
return
}
func InspectRoleAccess(parentObject string, skipUrl ...string) func(*context.Context) {
return func(c *context.Context) {
var validParentPermision bool
if len(skipUrl) > 0 {
requestUrl := c.Input.URL()
for _, url := range skipUrl {
if cachex.KeyMatch3(requestUrl, url) {
validParentPermision = true
break
}
}
}
// 跳过这个路由底下所有接口,使用父模块权限验证
if len(parentObject) > 0 && len(skipUrl) == 0 {
validParentPermision = true
}
CheckAuthorization(c)
if validParentPermision {
CheckRoleAccess(c, parentObject, c.Input.Method())
return
}
CheckRoleAccess(c, c.Input.URL(), c.Input.Method())
}
}