db_policy.go 997 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package perm
  2. import (
  3. "github.com/lib/pq"
  4. "gorm.io/gorm"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. type DefaultDBPolicy struct {
  10. gorm.Model
  11. ReferID string
  12. Subject string
  13. Effect string
  14. Actions pq.StringArray `gorm:"type:text[]"`
  15. Resources pq.StringArray `gorm:"type:text[]"`
  16. }
  17. func (p DefaultDBPolicy) LoadDBPolicies(db *gorm.DB, startFrom *time.Time) (toUpdate []*PolicyBuilder, toDelete []*PolicyBuilder) {
  18. var ps []DefaultDBPolicy
  19. if startFrom == nil || startFrom.IsZero() {
  20. db.Find(&ps)
  21. } else {
  22. db.Unscoped().Where("updated_at >= ? or deleted_at >= ?", startFrom, startFrom).Find(&ps)
  23. }
  24. for _, p := range ps {
  25. if p.DeletedAt.Valid {
  26. toDelete = append(toDelete, p.ToPolicy())
  27. } else {
  28. toUpdate = append(toUpdate, p.ToPolicy())
  29. }
  30. }
  31. return
  32. }
  33. func (p DefaultDBPolicy) ToPolicy() *PolicyBuilder {
  34. res := strings.Split(strings.Join(p.Resources, ","), ",")
  35. return PolicyFor(p.Subject).WhoAre(p.Effect).ToDo(p.Actions...).On(res...).ID(strconv.Itoa(int(p.ID)))
  36. }