【问题标题】:Rails 5 whitelist css property for sanitize helper清理助手的Rails 5白名单css属性
【发布时间】:2017-06-15 23:26:29
【问题描述】:

我需要允许sanitize(post.content) 的内联"style=position: absolute;" 输出。我发现documentation for Rails 4

config.action_view.sanitized_allowed_css_properties = ['position']

在 application.rb 中会将属性添加到白名单中,但我找不到文档是否仍然是 Rails 5 的情况,并且在多次重新启动服务器后似乎无法正常工作。有没有办法轻松添加列入白名单的 CSS 属性?这个answer for Rails 4 建议使用猴子补丁,但我不确定在哪里或如何这样做。

更新:安装 gem rails-deprecated_sanitized 允许上面的配置行工作,所以看起来 sanitized_allowed_css_properties 已被弃用。在 Rails 5 中肯定有办法做到这一点吗?我无法退回到 4,我需要将内联样式位置列入白名单才能使第三方插件工作(CKEditor + Iframely)

【问题讨论】:

    标签: css ruby-on-rails ruby-on-rails-5 sanitize


    【解决方案1】:

    您可以在 Rails 5 sanitizer 的 Loofah 中将多个 CSS 属性添加到白名单中。

    Loofah::HTML5::WhiteList::ALLOWED_CSS_PROPERTIES.merge %w(position background-image left list-style min-width top z-index)
    

    application.rb 中添加以上行 (再次不确定这有多安全)

    【讨论】:

    • 您可以正确地标记您的代码,方法是用“ `”包围它
    【解决方案2】:

    我完全不知道@Jim Hogan 试图用他的答案做什么。我试过了,但没有用。于是我花了一点时间分析一切,找到了自己的答案:

    我们从ActionController::Base.helpers 获得了一个名为sanitize_css 的助手。

    那么为什么不通过提取原始样式来使用它呢? Nokogiri 包含在 Rails > 4 中。

      def patched_sanitize(html_tag_string)
        sanitize html_tag_string, tags: %w(a b strong), attributes: manual_attributes
      end
    
      def manual_attributes
        attributes = %w(href target align)
        attributes << 'style' unless style_unsafe?
    
        attributes
      end
    
      def style_unsafe?
        ActionController::Base.helpers.sanitize_css(style_attributes_of(string)).empty?
      end
    
      def style_attributes_of(string)
        Nokogiri::HTML(self.body).xpath('//body').children.map{|e| e.attr('style')}.join(' ')
      end
    

    编辑:好的,我想我终于明白 OP 想说什么了。出于某种原因,只有当一个人按照我在这个答案中所做的事情时,它才会起作用。所以我猜我的答案是互补的:)

    【讨论】:

      【解决方案3】:

      处理this answer 和默认允许属性列表here,我最终添加了

      default_tags = Loofah::HTML5::WhiteList::ALLOWED_CSS_PROPERTIES.add('position')
      

      到 application.rb,默认情况下允许位置通过 sanitize。不确定这有多安全。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-15
        相关资源
        最近更新 更多