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 83 84 85 86 87 88 89 90 91 92
| import ( "context" "fmt"
"github.com/open-policy-agent/opa/rego" "github.com/open-policy-agent/opa/storage" "github.com/open-policy-agent/opa/storage/inmem" "github.com/open-policy-agent/opa/util" )
func main() { module := ` package example.authz
import rego.v1
default allow := false
allow if { input.method == "GET" input.path == ["salary", input.subject.user] data.example.users[_].name = input.subject.user }
allow if is_admin
is_admin if "admin" in input.subject.groups ` data := `{ "example": { "users": [ { "name": "alice", "likes": ["dogs", "clouds"] }, { "name": "bob", "likes": ["pizza", "cats"] } ] } }`
var json map[string]interface{}
err := util.UnmarshalJSON([]byte(data), &json) if err != nil { fmt.Println(err) }
store := inmem.NewFromObject(json)
ctx := context.TODO() query, err := rego.New( rego.Query("x = data.example.authz.allow"), rego.Module("example.rego", module), rego.Store(store), ).PrepareForEval(ctx)
if err != nil { }
input := map[string]interface{}{ "method": "GET", "path": []interface{}{"salary", "bob"}, "subject": map[string]interface{}{ "user": "bob", "groups": []interface{}{"sales", "marketing"}, }, }
results, err := query.Eval(ctx, rego.EvalInput(input)) if err != nil { fmt.Println(err) } else if len(results) == 0 { fmt.Println(err) }
v := results[0].Bindings["a"]
fmt.Println(v) }
|