-
Notifications
You must be signed in to change notification settings - Fork 5
/
gin_middleware.go
81 lines (75 loc) · 2.31 KB
/
gin_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
package opamiddleware
import (
"errors"
"github.com/Joffref/opa-middleware/config"
"github.com/Joffref/opa-middleware/internal"
"github.com/gin-gonic/gin"
"net/http"
)
type GinInputCreationMethod func(c *gin.Context) (map[string]interface{}, error)
type GinMiddleware struct {
Config *config.Config
// InputCreationMethod is a function that returns the value to be sent to the OPA server.
InputCreationMethod GinInputCreationMethod `json:"binding_method,omitempty"`
}
// NewGinMiddleware is the constructor for the opa gin middleware.
func NewGinMiddleware(cfg *config.Config, input GinInputCreationMethod) (*GinMiddleware, error) {
err := cfg.Validate()
if err != nil {
return nil, err
}
if input == nil {
if cfg.InputCreationMethod == nil {
return nil, errors.New("[opa-middleware-gin] InputCreationMethod must be provided")
}
input = func(c *gin.Context) (map[string]interface{}, error) {
bind, err := cfg.InputCreationMethod(c.Request)
if err != nil {
return nil, err
}
return bind, nil
}
}
return &GinMiddleware{
Config: cfg,
InputCreationMethod: input,
}, nil
}
// Use returns the handler for the middleware that is used by gin to evaluate the request against the policy.
func (g *GinMiddleware) Use() func(c *gin.Context) {
return func(c *gin.Context) {
if g.Config.Debug {
g.Config.Logger.Printf("[opa-middleware-gin] Request received")
}
result, err := g.query(c)
if err != nil {
if g.Config.Debug {
g.Config.Logger.Printf("[opa-middleware-gin] Error: %s", err.Error())
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if g.Config.Debug {
g.Config.Logger.Printf("[opa-middleware-gin] Result: %t", result)
}
if result != g.Config.ExceptedResult {
c.JSON(g.Config.DeniedStatusCode, gin.H{"error": g.Config.DeniedMessage})
c.AbortWithStatus(g.Config.DeniedStatusCode)
return
}
c.Next()
}
}
func (g *GinMiddleware) query(c *gin.Context) (bool, error) {
bind, err := g.InputCreationMethod(c)
if err != nil {
return !g.Config.ExceptedResult, err
}
if g.Config.URL != "" {
input := make(map[string]interface{})
input["input"] = bind
return internal.QueryURL(c.Request, g.Config, input)
}
return internal.QueryPolicy(c.Request, g.Config, bind)
}