Rails中html_escape和sanitize

本文介绍了Rails (ROR) 中处理用户输入HTML的方法,包括使用h()进行基本的HTML转义,sanitize()来限制特定的HTML标签及属性,以及自定义sanitize方法以允许特定的HTML标签。

       一般来说,通常使用input的field都会做一些filter的动作,避免被不怀好意之徒塞一些危险的 HTML code(script等)进去搞破坏。在ROR中,我们在前面加一个h()(一般不用括号?不容易看到?)即可,h在ROR中起什么作用呢?它是 html_escape的alias(别名),它会将所有的"<xx>"变成&lt;,&gt,比如:
js 代码 <script>alert('a');</script>会变成:    &lt;script&gt;alert('a');&lt;/script&gt;
这样就完全做不了乱了。因为所有的tag都被搞掉了。这样太严格了,有时候我们需要开放一些字体,颜色等tag给用户使用,用h()就不行了,正好ROR中还有个方法,sanitize()这个方法可以帮你实现这个愿望。ROR API中:
       Sanitizes the given HTML by making form and script tags into regular text, and removing all "onxxx" attributes (so that arbitrary Javascript cannot be executed). Also removes href attributes that start with "javascript:".
       
      它会砍掉script这个tag,以及onXxxx之类的attribut,你没有机会执行javascript,但是你还可以塞一些div或iframe之类的tag让你的版面烂掉。

      所以我们需要自定义一个html filter,可以自由的指定我们放行的那些tag。网上发现了这个sanitize.rb,完美的帮我们实现愿望。如何使用:
第一行:
ruby 代码
  1. def sanitize( html, okTags='a href, b, br, i, p' )  
okTags代表就是允许的tag,目前有a,b,br,i,p之类的tag,如果输入<iframe>xxx</iframe>之类的不允许的code,就会出现
xxx.不允许的结果都将被砍掉。如果想增加span,或font这样的tag,则可以:
ruby 代码
  1. def sanitize( html, okTags='a href, b, br, i, p, span, font' )  

a href之间没有用逗号隔开,是代表sanitize允许a这个tag使用href这个attribute,比如:
<a href=" http://blackanger.iteye.com" _fcksavedurl="http://lightyror.blogspot.com" target="_blank">Haha</a>
只会出现: <a href= http://blackanger.iteye.com>Haha</a>,只有href这个属性可以保留,其他的被无情的砍掉。当我们输入这样的代码:
            <a href= http://blackanger.iteye.com>Haha
会自动帮你补齐tag:

            <a href=http://blackanger.iteye.com>Haha</a>

Put the following code in your helper:
#
# $Id: sanitize.rb 3 2005-04-05 12:51:14Z dwight $
#
# Copyright (c) 2005 Dwight Shih
# A derived work of the Perl version:
# Copyright (c) 2002 Brad Choate, bradchoate.com
#
# Permission is hereby granted, free of charge, to
# any person obtaining a copy of this software and
# associated documentation files (the "Software"), to
# deal in the Software without restriction, including
# without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to
# whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission
# notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
# OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
# OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
# OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#

def sanitize( html, okTags='a href, b, br, i, p' )
# no closing tag necessary for these
soloTags = ["br","hr"]

# Build hash of allowed tags with allowed attributes
tags = okTags.downcase().split(',').collect!{ |s| s.split(' ') }
allowed = Hash.new
tags.each do |s|
    key = s.shift
    allowed[key] = s
end

# Analyze all <> elements
stack = Array.new
result = html.gsub( /(<.*?>)/m ) do | element |
    if element =~ /\A<\/(\w+)/ then
      # </tag>
      tag = $1.downcase
      if allowed.include?(tag) && stack.include?(tag) then
        # If allowed and on the stack
        # Then pop down the stack
        top = stack.pop
        out = "</#{top}>"
        until top == tag do
          top = stack.pop
          out << "</#{top}>"
        end
        out
      end
    elsif element =~ /\A<(\w+)\s*\/>/
      # <tag />
      tag = $1.downcase
      if allowed.include?(tag) then
        "<#{tag} />"
      end
    elsif element =~ /\A<(\w+)/ then
      # <tag ...>
      tag = $1.downcase
      if allowed.include?(tag) then
        if ! soloTags.include?(tag) then
          stack.push(tag)
        end
        if allowed[tag].length == 0 then
          # no allowed attributes
          "<#{tag}>"
        else
          # allowed attributes?
          out = "<#{tag}"
          while ( $' =~ /(\w+)=("[^"]+")/ )
            attr = $1.downcase
            valu = $2
            if allowed[tag].include?(attr) then
              out << " #{attr}=#{valu}"
            end
          end
          out << ">"
        end
      end
    end
end

# eat up unmatched leading >
while result.sub!(/\A([^<]*)>/m) { $1 } do end

# eat up unmatched trailing <
while result.sub!(/<([^>]*)\Z/m) { $1 } do end

# clean up the stack
if stack.length > 0 then
    result << "</#{stack.reverse.join('></')}>"
end

result
end

内容概要:本文详细介绍了“秒杀商城”微服务架构的设计与实战全过程,涵盖系统从需求分析、服务拆分、技术选型到核心功能开发、分布式事务处理、容器化部署及监控链路追踪的完整流程。重点解决了高并发场景下的超卖问题,采用Redis预减库存、消息队列削峰、数据库乐观锁等手段保障数据一致性,并通过Nacos实现服务注册发现与配置管理,利用Seata处理跨服务分布式事务,结合RabbitMQ实现异步下单,提升系统吞吐能力。同时,项目支持Docker Compose快速部署Kubernetes生产级编排,集成Sleuth+Zipkin链路追踪与Prometheus+Grafana监控体系,构建可观测性强的微服务系统。; 适合人群:具备Java基础Spring Boot开发经验,熟悉微服务基本概念的中高级研发人员,尤其是希望深入理解高并发系统设计、分布式事务、服务治理等核心技术的开发者;适合工作2-5年、有志于转型微服务或提升架构能力的工程师; 使用场景及目标:①学习如何基于Spring Cloud Alibaba构建完整的微服务项目;②掌握秒杀场景下高并发、超卖控制、异步化、削峰填谷等关键技术方案;③实践分布式事务(Seata)、服务熔断降级、链路追踪、统一配置中心等企业级中间件的应用;④完成从本地开发到容器化部署的全流程落地; 阅读建议:建议按照文档提供的七个阶段循序渐进地动手实践,重点关注秒杀流程设计、服务间通信机制、分布式事务实现系统性能优化部分,结合代码调试与监控工具深入理解各组件协作原理,真正掌握高并发微服务系统的构建能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值