permission.rb 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class KnowledgeBase::Permission < ApplicationModel
  3. belongs_to :permissionable, polymorphic: true, touch: true
  4. belongs_to :role
  5. validates :role, uniqueness: { scope: %i[permissionable_id permissionable_type] }
  6. validate :ensure_access_matches_role
  7. # cache key for calculated permissions
  8. # @param permissionable [KnowledgeBase::Category, KnowledgeBase]
  9. # @return [String]
  10. def self.cache_key(permissionable)
  11. "#{self}/#{latest_change}/#{permissionable.class}/#{permissionable.class.latest_change}/permission/#{permissionable.id}"
  12. end
  13. private
  14. def ensure_access_matches_role
  15. return if role.blank?
  16. return if allowed_access.include? access
  17. errors.add :base, __('This permission level is not available based on the current roles permissions.')
  18. end
  19. def allowed_access
  20. if role.with_permission? 'knowledge_base.editor'
  21. %w[editor reader none]
  22. elsif role.with_permission? 'knowledge_base.reader'
  23. %w[reader none]
  24. else
  25. []
  26. end
  27. end
  28. end