Commit f9dd1402807a42eec2b56354b0c2a7778433c7f5

Authored by Dmitriy Zaporozhets
2 parents 0d475208 4a03bbe4

Merge branch 'add_noreferrer_to_all_links' into 'master'

Add nofollow to all external links

Fixes #1224
app/helpers/application_helper.rb
... ... @@ -231,4 +231,31 @@ module ApplicationHelper
231 231 content_tag(:i, nil, class: 'icon-spinner icon-spin') + text
232 232 end
233 233 end
  234 +
  235 + def link_to(name = nil, options = nil, html_options = nil, &block)
  236 + begin
  237 + uri = URI(options)
  238 + host = uri.host
  239 + absolute_uri = uri.absolute?
  240 + rescue URI::InvalidURIError, ArgumentError
  241 + host = nil
  242 + absolute_uri = nil
  243 + end
  244 +
  245 + # Add "nofollow" only to external links
  246 + if host && host != Gitlab.config.gitlab.host && absolute_uri
  247 + if html_options
  248 + if html_options[:rel]
  249 + html_options[:rel] << " nofollow"
  250 + else
  251 + html_options.merge!(rel: "nofollow")
  252 + end
  253 + else
  254 + html_options = Hash.new
  255 + html_options[:rel] = "nofollow"
  256 + end
  257 + end
  258 +
  259 + super
  260 + end
234 261 end
... ...
spec/helpers/application_helper_spec.rb
... ... @@ -195,4 +195,27 @@ describe ApplicationHelper do
195 195 simple_sanitize(input).should == a_tag
196 196 end
197 197 end
  198 +
  199 + describe "link_to" do
  200 +
  201 + it "should not include rel=nofollow for internal links" do
  202 + expect(link_to("Home", root_path)).to eq("<a href=\"/\">Home</a>")
  203 + end
  204 +
  205 + it "should include rel=nofollow for external links" do
  206 + expect(link_to("Example", "http://www.example.com")).to eq("<a href=\"http://www.example.com\" rel=\"nofollow\">Example</a>")
  207 + end
  208 +
  209 + it "should include re=nofollow for external links and honor existing html_options" do
  210 + expect(
  211 + link_to("Example", "http://www.example.com", class: "toggle", data: {toggle: "dropdown"})
  212 + ).to eq("<a class=\"toggle\" data-toggle=\"dropdown\" href=\"http://www.example.com\" rel=\"nofollow\">Example</a>")
  213 + end
  214 +
  215 + it "should include rel=nofollow for external links and preserver other rel values" do
  216 + expect(
  217 + link_to("Example", "http://www.example.com", rel: "noreferrer")
  218 + ).to eq("<a href=\"http://www.example.com\" rel=\"noreferrer nofollow\">Example</a>")
  219 + end
  220 + end
198 221 end
... ...