permission.rb 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Permission < ApplicationModel
  3. include ChecksClientNotification
  4. include ChecksHtmlSanitized
  5. include HasCollectionUpdate
  6. has_and_belongs_to_many :roles
  7. store :preferences
  8. validates :name, presence: true
  9. # This is added to handle migrations from before the columns were modified.
  10. # For example when upgrading from pre-6.4.
  11. # Otherwise older migrations fail since those columnsa are not yet available.
  12. with_options if: -> { respond_to?(:label) && respond_to?(:description) } do
  13. validates :label, length: { maximum: 255 }
  14. validates :description, length: { maximum: 500 }
  15. end
  16. sanitized_html :description
  17. # Returns permission name with parent permission names
  18. #
  19. # @return [String]
  20. #
  21. # @example
  22. # Permission.with_parents('some_key.sub_key')
  23. # #=> ['some_key.sub_key', 'some_key']
  24. def self.with_parents(key)
  25. key
  26. .split('.')
  27. .each_with_object([]) do |elem, memo|
  28. memo << if (previous = memo.last)
  29. "#{previous}.#{elem}"
  30. else
  31. elem
  32. end
  33. end
  34. end
  35. def to_s
  36. name
  37. end
  38. def self.join_with(object, permissions)
  39. return object if !object.method_defined?(:permissions?)
  40. permissions = with_parents(permissions)
  41. object
  42. .joins(roles: :permissions)
  43. .where(roles: { active: true }, permissions: { name: permissions, active: true })
  44. end
  45. end