Commit 4a03bbe4831399381a45cde7fd19ecfb67895bd4

Authored by Marin Jankovski
1 parent 3910b591

Add nofollow to all internal links.

app/helpers/application_helper.rb
... ... @@ -233,16 +233,29 @@ module ApplicationHelper
233 233 end
234 234  
235 235 def link_to(name = nil, options = nil, html_options = nil, &block)
236   - if html_options
237   - if html_options[:rel]
238   - html_options[:rel] << " noreferrer"
  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
239 253 else
240   - html_options.merge(rel: "noreferrer")
  254 + html_options = Hash.new
  255 + html_options[:rel] = "nofollow"
241 256 end
242   - else
243   - html_options = Hash.new
244   - html_options[:rel] = "noreferrer"
245 257 end
  258 +
246 259 super
247 260 end
248 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
... ...