This repository has been archived by the owner on Sep 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
90 lines (76 loc) · 1.98 KB
/
middleware.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
package middleware
import (
"net/http"
"github.com/chadhao/logit/config"
"github.com/chadhao/logit/middleware/jwt"
"github.com/chadhao/logit/modules/user/constant"
"github.com/chadhao/logit/router"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func LoadBeforeRouter(e *echo.Echo, con config.Config, r router.Router) {
// Routes and Config injection
e.Pre(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set("config", con)
c.Set("router", r)
return next(c)
}
})
e.Pre(middleware.RemoveTrailingSlash())
}
func LoadAfterRouter(e *echo.Echo, c config.Config) {
// CORS handling
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
}))
// JWT handling
jwtAccessSigningKey, _ := c.Get("system.jwt.access.key")
e.Use(jwt.JWTWithConfig(jwt.JWTConfig{
Skipper: func(e echo.Context) bool {
r := e.Get("router").(router.Router)
route, err := r.Match(e.Request().Method, e.Path())
if err != nil {
return true
}
return len(route.Roles) == 0
},
SigningKey: []byte(jwtAccessSigningKey),
}))
//Authorization
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(e echo.Context) error {
r := e.Get("router").(router.Router)
route, err := r.Match(e.Request().Method, e.Path())
if err != nil {
return err
}
if len(route.Roles) == 0 {
return next(e)
}
userRoles := e.Get("roles").([]int)
if hasIntersectionInt(route.Roles, userRoles) {
return next(e)
}
// 用户身份仅为user时候也pass
if len(route.Roles) > 0 && route.Roles[0] == constant.ROLE_USER_DEFAULT {
return next(e)
}
return echo.NewHTTPError(http.StatusUnauthorized)
}
})
}
func hasIntersectionInt(a []int, b []int) bool {
i := make(map[int]bool, 0)
for _, v := range a {
i[v] = true
}
for _, v := range b {
if _, ok := i[v]; ok {
return true
}
}
return false
}