From 4a03bbe4831399381a45cde7fd19ecfb67895bd4 Mon Sep 17 00:00:00 2001 From: Marin Jankovski Date: Fri, 30 May 2014 17:09:31 +0200 Subject: [PATCH] Add nofollow to all internal links. --- app/helpers/application_helper.rb | 27 ++++++++++++++++++++------- spec/helpers/application_helper_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 4a3b345..198ca76 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -233,16 +233,29 @@ module ApplicationHelper end def link_to(name = nil, options = nil, html_options = nil, &block) - if html_options - if html_options[:rel] - html_options[:rel] << " noreferrer" + begin + uri = URI(options) + host = uri.host + absolute_uri = uri.absolute? + rescue URI::InvalidURIError, ArgumentError + host = nil + absolute_uri = nil + end + + # Add "nofollow" only to external links + if host && host != Gitlab.config.gitlab.host && absolute_uri + if html_options + if html_options[:rel] + html_options[:rel] << " nofollow" + else + html_options.merge!(rel: "nofollow") + end else - html_options.merge(rel: "noreferrer") + html_options = Hash.new + html_options[:rel] = "nofollow" end - else - html_options = Hash.new - html_options[:rel] = "noreferrer" end + super end end diff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rb index 0376e0a..10c5617 100644 --- a/spec/helpers/application_helper_spec.rb +++ b/spec/helpers/application_helper_spec.rb @@ -195,4 +195,27 @@ describe ApplicationHelper do simple_sanitize(input).should == a_tag end end + + describe "link_to" do + + it "should not include rel=nofollow for internal links" do + expect(link_to("Home", root_path)).to eq("Home") + end + + it "should include rel=nofollow for external links" do + expect(link_to("Example", "http://www.example.com")).to eq("Example") + end + + it "should include re=nofollow for external links and honor existing html_options" do + expect( + link_to("Example", "http://www.example.com", class: "toggle", data: {toggle: "dropdown"}) + ).to eq("Example") + end + + it "should include rel=nofollow for external links and preserver other rel values" do + expect( + link_to("Example", "http://www.example.com", rel: "noreferrer") + ).to eq("Example") + end + end end -- libgit2 0.21.2