forked from content-services/content-sources-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrbac.go
75 lines (62 loc) · 1.94 KB
/
rbac.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
package middleware
import (
"strings"
path_util "github.com/content-services/content-sources-backend/pkg/handler/utils"
"github.com/content-services/content-sources-backend/pkg/rbac"
"github.com/labstack/echo/v4"
echo_middleware "github.com/labstack/echo/v4/middleware"
"github.com/rs/zerolog"
)
// This middleware will add rbac feature to the service
// https://echo.labstack.com/cookbook/middleware/
// https://github.com/labstack/echo/tree/master/middleware
const (
xrhidHeader = "X-Rh-Identity"
)
type Rbac struct {
BaseUrl string
Skipper echo_middleware.Skipper
Client rbac.ClientWrapper
PermissionsMap *rbac.PermissionsMap
}
func NewRbac(config Rbac) echo.MiddlewareFunc {
if config.PermissionsMap == nil {
panic("PermissionsMap cannot be nil")
}
if config.Client == nil {
panic("client cannot be nil")
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
logger := zerolog.Ctx(c.Request().Context())
path := MatchedRoute(c)
if config.Skipper != nil && config.Skipper(c) {
return next(c)
}
if path = strings.Join(path_util.NewPathWithString(path).RemovePrefixes(), "/"); path == "" {
return echo.ErrBadRequest
}
method := c.Request().Method
resource, verb, err := config.PermissionsMap.Permission(method, path)
if err != nil {
logger.Error().Msgf("No mapping found for method=%s path=%s:%s", method, path, err.Error())
return echo.ErrUnauthorized
}
xrhid := c.Request().Header.Get(xrhidHeader)
if xrhid == "" {
logger.Error().Msg("x-rh-identity is required")
return echo.ErrBadRequest
}
allowed, err := config.Client.Allowed(c.Request().Context(), resource, verb)
if err != nil {
logger.Error().Msgf("error checking permissions: %s", err.Error())
return echo.ErrUnauthorized
}
if !allowed {
logger.Error().Msgf("request not allowed")
return echo.ErrUnauthorized
}
return next(c)
}
}
}