builder.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package perm
  2. import (
  3. "crypto/md5"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "reflect"
  8. "strings"
  9. "time"
  10. "github.com/iancoleman/strcase"
  11. "github.com/jinzhu/inflection"
  12. "github.com/ory/ladon"
  13. "github.com/ory/ladon/manager/memory"
  14. "github.com/sunfmin/reflectutils"
  15. "gorm.io/gorm"
  16. )
  17. const (
  18. Allowed = ladon.AllowAccess
  19. Denied = ladon.DenyAccess
  20. Anything = "*"
  21. Anybody = "*"
  22. Anonymous = "anonymous"
  23. )
  24. var PermissionDenied = errors.New("permission denied")
  25. type Context = ladon.Context
  26. type Conditions = ladon.Conditions
  27. type SubjectsFunc func(r *http.Request) []string
  28. type ContextFunc func(r *http.Request, objs []interface{}) Context
  29. type DBPolicy interface {
  30. LoadDBPolicies(db *gorm.DB, startFrom *time.Time) ([]*PolicyBuilder, []*PolicyBuilder)
  31. }
  32. type permRNer interface {
  33. PermissionRN() []string
  34. }
  35. func ToPermissionRN(v interface{}) []string {
  36. if pr, ok := v.(permRNer); ok {
  37. return pr.PermissionRN()
  38. }
  39. typeName := fmt.Sprint(reflect.TypeOf(v))
  40. ss := strings.Split(typeName, ".")
  41. typeName = ss[len(ss)-1]
  42. typeName = strings.NewReplacer("*", "", ".", "-").Replace(typeName)
  43. typeName = strcase.ToSnake(inflection.Plural(typeName))
  44. id, err := reflectutils.Get(v, "ID")
  45. if err == nil && len(fmt.Sprint(id)) > 0 && fmt.Sprint(id) != "0" {
  46. return []string{typeName, fmt.Sprint(id)}
  47. }
  48. return []string{typeName}
  49. }
  50. type Builder struct {
  51. policies []*PolicyBuilder
  52. ladon *ladon.Ladon
  53. subjectsFunc SubjectsFunc
  54. contextFunc ContextFunc
  55. dbPolicyModel DBPolicy
  56. }
  57. func New() *Builder {
  58. return &Builder{
  59. ladon: &ladon.Ladon{
  60. Manager: memory.NewMemoryManager(),
  61. Matcher: &PathMatcher{},
  62. },
  63. }
  64. }
  65. func (b *Builder) Policies(ps ...*PolicyBuilder) (r *Builder) {
  66. b.policies = ps
  67. for _, p := range b.policies {
  68. if p.policy.ID == "" {
  69. p.policy.ID = fmt.Sprintf("%x", md5.Sum(p.Json()))
  70. }
  71. err := b.ladon.Manager.Create(p.policy)
  72. if err != nil {
  73. panic(err)
  74. }
  75. }
  76. return b
  77. }
  78. func (b *Builder) SubjectsFunc(v SubjectsFunc) (r *Builder) {
  79. b.subjectsFunc = v
  80. return b
  81. }
  82. func (b *Builder) ContextFunc(v ContextFunc) (r *Builder) {
  83. b.contextFunc = v
  84. return b
  85. }
  86. func (b *Builder) EnableDBPolicy(db *gorm.DB, dbPolicyModel DBPolicy, loadDuration time.Duration) (r *Builder) {
  87. if dbPolicyModel == nil {
  88. b.dbPolicyModel = DefaultDBPolicy{}
  89. } else {
  90. b.dbPolicyModel = dbPolicyModel
  91. }
  92. go b.loopLoadDBPolicies(db, loadDuration)
  93. return b
  94. }
  95. func (b *Builder) UpdatePolicies(toUpdate ...*PolicyBuilder) {
  96. for _, p := range toUpdate {
  97. b.ladon.Manager.Update(p.policy)
  98. }
  99. }
  100. func (b *Builder) DeletePolicies(toDelete ...*PolicyBuilder) {
  101. for _, p := range toDelete {
  102. b.ladon.Manager.Delete(p.GetID())
  103. }
  104. }
  105. func (b *Builder) LoadDBPoliciesToMemory(db *gorm.DB, startFrom *time.Time) {
  106. toUpdate, toDelete := b.dbPolicyModel.LoadDBPolicies(db, startFrom)
  107. b.DeletePolicies(toDelete...)
  108. b.UpdatePolicies(toUpdate...)
  109. if Verbose {
  110. b.printPolices()
  111. }
  112. }
  113. func (b *Builder) loopLoadDBPolicies(db *gorm.DB, duration time.Duration) {
  114. now := time.Now()
  115. b.LoadDBPoliciesToMemory(db, nil)
  116. for next := range time.Tick(duration) {
  117. b.LoadDBPoliciesToMemory(db, &now)
  118. now = next
  119. }
  120. }
  121. func (b *Builder) printPolices() {
  122. allp, _ := b.ladon.Manager.GetAll(100, 0)
  123. for _, p := range allp {
  124. fmt.Printf("%+v \n", p)
  125. }
  126. }