This repository has been archived by the owner on Aug 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpolicy.go
82 lines (66 loc) · 1.92 KB
/
policy.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
package gateway
import (
"github.com/dgrijalva/jwt-go"
"github.com/kenfdev/opa-api-auth-go/entity"
"github.com/labstack/echo"
"github.com/sirupsen/logrus"
"regexp"
)
type PolicyGateway interface {
Ask(echo.Context) bool
}
type PolicyLocalGateway struct {
getSalaryPathRegex *regexp.Regexp
}
func NewPolicyLocalGateway() *PolicyLocalGateway {
return &PolicyLocalGateway{
getSalaryPathRegex: regexp.MustCompile("GET /finance/salary/.*"),
}
}
// Ask checks if an action is permitted as it inspects the request context
func (gw *PolicyLocalGateway) Ask(c echo.Context) bool {
path := c.Request().Method + " " + c.Path()
raw := c.Get("token").(*jwt.Token)
claims := raw.Claims.(*entity.TokenClaims)
var allow = false
switch {
case gw.getSalaryPathRegex.MatchString(path):
allow = gw.checkGETSalary(c, claims)
}
return allow
}
func (gw *PolicyLocalGateway) checkGETSalary(c echo.Context, claims *entity.TokenClaims) bool {
userID := c.Param("id")
logrus.WithFields(logrus.Fields{
"userID": userID,
"claims": claims,
}).Info("Checking GET salary policies")
if yes := gw.checkIfOwner(userID, claims); yes {
logrus.Info("Allowing because requester is the owner")
return true
}
if yes := gw.checkIfSubordinate(userID, claims); yes {
logrus.Info("Allowing because target is a subordinate of requester")
return true
}
if yes := gw.checkIfHR(claims); yes {
logrus.Info("Allowing because requester is a member of HR")
return true
}
logrus.Info("Denying request")
return false
}
func (*PolicyLocalGateway) checkIfOwner(userID string, claims *entity.TokenClaims) bool {
return userID == claims.User
}
func (*PolicyLocalGateway) checkIfSubordinate(userID string, claims *entity.TokenClaims) bool {
for _, subordinate := range claims.Subordinates {
if subordinate == userID {
return true
}
}
return false
}
func (*PolicyLocalGateway) checkIfHR(claims *entity.TokenClaims) bool {
return claims.BelongsToHR
}