policy.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package perm
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "github.com/ory/ladon"
  6. )
  7. type PolicyBuilder struct {
  8. policy *ladon.DefaultPolicy
  9. module string
  10. }
  11. func PolicyFor(subjects ...string) *PolicyBuilder {
  12. return &PolicyBuilder{
  13. policy: &ladon.DefaultPolicy{
  14. Subjects: subjects,
  15. },
  16. }
  17. }
  18. func (b *PolicyBuilder) Module(module string) (r *PolicyBuilder) {
  19. b.module = module
  20. return b
  21. }
  22. func (b *PolicyBuilder) ID(id string) (r *PolicyBuilder) {
  23. b.policy.ID = id
  24. return b
  25. }
  26. func (b *PolicyBuilder) WhoAre(effect string) (r *PolicyBuilder) {
  27. b.policy.Effect = effect
  28. return b
  29. }
  30. func (b *PolicyBuilder) ToDo(actions ...string) (r *PolicyBuilder) {
  31. b.policy.Actions = actions
  32. return b
  33. }
  34. func (b *PolicyBuilder) On(resources ...string) (r *PolicyBuilder) {
  35. if b.module == "" {
  36. b.policy.Resources = append(b.policy.Resources, resources...)
  37. return b
  38. }
  39. var newRes []string
  40. for _, res := range resources {
  41. newRes = append(newRes, strings.Join([]string{b.module, res}, ":"))
  42. }
  43. b.policy.Resources = append(b.policy.Resources, newRes...)
  44. return b
  45. }
  46. func (b *PolicyBuilder) Given(conditions Conditions) (r *PolicyBuilder) {
  47. b.policy.Conditions = conditions
  48. return b
  49. }
  50. func (b PolicyBuilder) Json() []byte {
  51. str, _ := json.Marshal(b.policy)
  52. return str
  53. }
  54. func (b *PolicyBuilder) GetID() string {
  55. return b.policy.ID
  56. }