ms-tester/internal/contests/usecase/policy_agent.go

40 lines
799 B
Go
Raw Normal View History

2024-10-09 19:04:37 +00:00
package usecase
2024-08-20 11:18:23 +00:00
import (
"context"
2024-10-13 16:21:12 +00:00
"git.sch9.ru/new_gate/ms-tester/internal/models"
2024-08-20 11:18:23 +00:00
"github.com/open-policy-agent/opa/rego"
)
type PermissionService struct {
query *rego.PreparedEvalQuery
}
func NewPermissionService() *PermissionService {
query, err := rego.New(
rego.Query("allow = data.problem.rbac.allow"),
2024-10-13 14:03:43 +00:00
rego.Load([]string{"./opa/problem.rego"}, nil),
2024-08-20 11:18:23 +00:00
).PrepareForEval(context.TODO())
if err != nil {
panic(err)
}
return &PermissionService{
query: &query,
}
}
func (s *PermissionService) Allowed(ctx context.Context, user *models.User, action string) bool {
input := map[string]interface{}{
"user": user,
"action": action,
}
result, err := s.query.Eval(ctx, rego.EvalInput(input))
if err != nil {
panic(err)
}
return result[0].Bindings["allow"].(bool)
}