From dbc4abc58700bd48bef90650d3e7d8ec85f8bfd3 Mon Sep 17 00:00:00 2001 From: Bolarinwa Balogun Date: Wed, 26 Jun 2019 09:02:11 -0400 Subject: [PATCH] Add rel="nofollow" to links in comments (#3304) * Add rel="nofollow" to links in comments * Improve code quality and Add tests --- app/labor/markdown_parser.rb | 5 +++-- app/models/comment.rb | 2 +- spec/models/comment_spec.rb | 6 ++++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/labor/markdown_parser.rb b/app/labor/markdown_parser.rb index 3a59d35fe..84d506a38 100644 --- a/app/labor/markdown_parser.rb +++ b/app/labor/markdown_parser.rb @@ -6,8 +6,9 @@ class MarkdownParser @content = content end - def finalize - renderer = Redcarpet::Render::HTMLRouge.new(hard_wrap: true, filter_html: false) + def finalize(link_attributes: {}) + options = { hard_wrap: true, filter_html: false, link_attributes: link_attributes } + renderer = Redcarpet::Render::HTMLRouge.new(options) markdown = Redcarpet::Markdown.new(renderer, REDCARPET_CONFIG) catch_xss_attempts(@content) escaped_content = escape_liquid_tags_in_codeblock(@content) diff --git a/app/models/comment.rb b/app/models/comment.rb index b791466a2..d273055b1 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -213,7 +213,7 @@ class Comment < ApplicationRecord def evaluate_markdown fixed_body_markdown = MarkdownFixer.fix_for_comment(body_markdown) parsed_markdown = MarkdownParser.new(fixed_body_markdown) - self.processed_html = parsed_markdown.finalize + self.processed_html = parsed_markdown.finalize(link_attributes: { rel: "nofollow" }) wrap_timestamps_if_video_present! shorten_urls! end diff --git a/spec/models/comment_spec.rb b/spec/models/comment_spec.rb index 9997890d0..97ae07f78 100644 --- a/spec/models/comment_spec.rb +++ b/spec/models/comment_spec.rb @@ -79,6 +79,12 @@ RSpec.describe Comment, type: :model do expect(comment.processed_html.include?(">1:52:30")).to eq(false) end + it "adds rel=nofollow to links" do + comment.body_markdown = "this is a comment with a link: http://dev.to" + comment.save + expect(comment.processed_html.include?('rel="nofollow"')).to eq(true) + end + it "adds a mention url if user is mentioned like @mention" do comment.body_markdown = "Hello @#{user.username}, you are cool." comment.save