policy.go 1.4 KB

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