-
Notifications
You must be signed in to change notification settings - Fork 5
/
echo_middleware.go
76 lines (70 loc) · 2.08 KB
/
echo_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
package opamiddleware
import (
"errors"
"github.com/Joffref/opa-middleware/config"
"github.com/Joffref/opa-middleware/internal"
"github.com/labstack/echo/v4"
"net/http"
)
type EchoInputCreationMethod func(c echo.Context) (map[string]interface{}, error)
type EchoMiddleware struct {
Config *config.Config
InputCreationMethod EchoInputCreationMethod `json:"binding_method,omitempty"`
}
func NewEchoMiddleware(cfg *config.Config, input EchoInputCreationMethod) (*EchoMiddleware, error) {
err := cfg.Validate()
if err != nil {
return nil, err
}
if input == nil {
if cfg.InputCreationMethod == nil {
return nil, errors.New("[opa-middleware-echo] InputCreationMethod must be provided")
}
input = func(c echo.Context) (map[string]interface{}, error) {
bind, err := cfg.InputCreationMethod(c.Request())
if err != nil {
return nil, err
}
return bind, nil
}
}
return &EchoMiddleware{
Config: cfg,
InputCreationMethod: input,
}, nil
}
func (e *EchoMiddleware) Use() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if e.Config.Debug {
e.Config.Logger.Printf("[opa-middleware-echo] Request received")
}
result, err := e.query(c)
if err != nil {
if e.Config.Debug {
e.Config.Logger.Printf("[opa-middleware-echo] Error: %s", err.Error())
}
return c.JSON(http.StatusInternalServerError, map[string]interface{}{"error": err.Error()})
}
if e.Config.Debug {
e.Config.Logger.Printf("[opa-middleware-echo] Result: %t", result)
}
if result != e.Config.ExceptedResult {
return c.JSON(e.Config.DeniedStatusCode, map[string]interface{}{"error": e.Config.DeniedMessage})
}
return next(c)
}
}
}
func (e *EchoMiddleware) query(c echo.Context) (bool, error) {
bind, err := e.InputCreationMethod(c)
if err != nil {
return !e.Config.ExceptedResult, err
}
if e.Config.URL != "" {
input := make(map[string]interface{})
input["input"] = bind
return internal.QueryURL(c.Request(), e.Config, input)
}
return internal.QueryPolicy(c.Request(), e.Config, bind)
}