db_policy.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package perm
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. "github.com/lib/pq"
  7. "gorm.io/gorm"
  8. )
  9. type DBPolicyBuilder struct {
  10. db *gorm.DB
  11. model DBPolicy
  12. loadFrequency time.Duration
  13. }
  14. func NewDBPolicy(db *gorm.DB) *DBPolicyBuilder {
  15. return &DBPolicyBuilder{
  16. db: db,
  17. model: DefaultDBPolicy{},
  18. loadFrequency: time.Minute,
  19. }
  20. }
  21. func (dpb *DBPolicyBuilder) Model(m DBPolicy) *DBPolicyBuilder {
  22. dpb.model = m
  23. return dpb
  24. }
  25. func (dpb *DBPolicyBuilder) LoadFrequency(d time.Duration) *DBPolicyBuilder {
  26. dpb.loadFrequency = d
  27. return dpb
  28. }
  29. type DefaultDBPolicy struct {
  30. gorm.Model
  31. ReferID string
  32. Subject string
  33. Effect string
  34. Actions pq.StringArray `gorm:"type:text[]"`
  35. Resources pq.StringArray `gorm:"type:text[]"`
  36. }
  37. func (p DefaultDBPolicy) LoadDBPolicies(db *gorm.DB, startFrom *time.Time) (toUpdateOrCreate []*PolicyBuilder, toDelete []*PolicyBuilder) {
  38. var ps []DefaultDBPolicy
  39. if startFrom == nil || startFrom.IsZero() {
  40. db.Find(&ps)
  41. } else {
  42. db.Unscoped().Where("updated_at >= ? or deleted_at >= ?", startFrom, startFrom).Find(&ps)
  43. }
  44. for _, p := range ps {
  45. if p.DeletedAt.Valid {
  46. toDelete = append(toDelete, p.ToPolicy())
  47. } else {
  48. toUpdateOrCreate = append(toUpdateOrCreate, p.ToPolicy())
  49. }
  50. }
  51. return
  52. }
  53. func (p DefaultDBPolicy) ToPolicy() *PolicyBuilder {
  54. res := strings.Split(strings.Join(p.Resources, ","), ",")
  55. return PolicyFor(p.Subject).WhoAre(p.Effect).ToDo(p.Actions...).On(res...).ID(strconv.Itoa(int(p.ID)))
  56. }