checks_html_sanitized.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module ChecksHtmlSanitized
  3. extend ActiveSupport::Concern
  4. included do
  5. before_create :sanitized_html_attributes
  6. before_update :sanitized_html_attributes
  7. end
  8. def sanitized_html_attributes
  9. html_attributes = self.class.instance_variable_get(:@sanitized_html) || []
  10. return true if html_attributes.blank?
  11. options = self.class.instance_variable_get(:@sanitized_html_kwargs).slice(:no_images)
  12. sanitizer = HtmlSanitizer::Strict.new(**options)
  13. html_attributes.each do |attr|
  14. sanitize_single_attribute(attr, sanitizer)
  15. end
  16. true
  17. end
  18. def sanitizeable?(_attribute, _value)
  19. true
  20. end
  21. private
  22. def sanitize_single_attribute(attr, sanitizer)
  23. return if changes[attr].blank?
  24. value = send(attr)
  25. return if value.blank?
  26. return if !sanitizeable?(attr, value)
  27. send(:"#{attr}=", sanitizer.sanitize(value))
  28. end
  29. # methods defined here are going to extend the class, not the instance of it
  30. class_methods do
  31. =begin
  32. serve method to mark HTML attributes that need to get sanitized
  33. class Model < ApplicationModel
  34. include Sanitized
  35. sanitized_html :body
  36. end
  37. =end
  38. def sanitized_html(*attributes, **kwargs)
  39. @sanitized_html = attributes
  40. @sanitized_html_kwargs = kwargs
  41. end
  42. end
  43. end