diff options
Diffstat (limited to 'pkg/policies/init.go')
| -rw-r--r-- | pkg/policies/init.go | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/pkg/policies/init.go b/pkg/policies/init.go new file mode 100644 index 0000000..9916b11 --- /dev/null +++ b/pkg/policies/init.go @@ -0,0 +1,72 @@ +package policies + +import ( + "embed" + _ "embed" + "encoding/json" + "fmt" + "io/fs" + "log" + + "github.com/cedar-policy/cedar-go" + "github.com/cedar-policy/cedar-go/types" + "github.com/xlgmokha/x/pkg/x" +) + +//go:embed *.cedar +var files embed.FS + +var All *cedar.PolicySet = cedar.NewPolicySet() + +const entitiesJSON = `[ + { + "uid": { "type": "User", "id": "alice" }, + "attrs": { "age": 18 }, + "parents": [] + }, + { + "uid": { "type": "Photo", "id": "VacationPhoto94.jpg" }, + "attrs": {}, + "parents": [{ "type": "Album", "id": "jane_vacation" }] + } +]` + +func init() { + err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + if d.IsDir() { + return nil + } + + content, err := fs.ReadFile(files, path) + if err != nil { + return err + } + + var policy cedar.Policy + if err := policy.UnmarshalCedar(content); err != nil { + return err + } + + All.Add(cedar.PolicyID(path), &policy) + return nil + }) + + if err != nil { + log.Fatal(err) + } +} + +func Allowed(request cedar.Request) bool { + var entities cedar.EntityMap + x.Check(json.Unmarshal([]byte(entitiesJSON), &entities)) + + ok, diagnostic := All.IsAuthorized(entities, request) + if len(diagnostic.Errors) > 0 || len(diagnostic.Reasons) > 0 { + fmt.Printf("%v %v\n", diagnostic.Errors, diagnostic.Reasons) + } + return ok == types.Allow +} |
