Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails3 and safe nl2br !

I have a system for the users to be able to post comments.

The comments are grasped into a textarea.

My problem is to format the comments with br tag to replace \n

In fact, i could do something like that

s.gsub(/\n/, '<br />')

But the xss protection including in rails escapes br tags.

So i could do this

s.gsub(/\n/, '<br />').html_safe

But then, all the tags are accepted even script.... causing a big security problem

So my question is : how to format text with br safely ?

Thanks

EDIT: For now, i have add this

  def sanitaze
    self.gsub(/(<.*?>)/, '')
  end

  def nl2br
    self.sanitaze.gsub(/\n/, '<br />').html_safe
  end
like image 565
Arkan Avatar asked May 16 '10 15:05

Arkan


3 Answers

As Ryan Bigg suggested simple_format is the best tool for the job: it's 'l safe' and much neater than other solutions.

so for @var:

<%= simple_format(@var) %>

If you need to sanitize the text to get rid of HTML tags, you should do this before passing it to simple_format

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

like image 100
Jim Avatar answered Nov 19 '22 12:11

Jim


The best way I can figure to go about this is using the sanitize method to strip all but the BR tag we want.

Assume that we have @var with the content "some\ntext":

Trying <%= @var.gsub(/\n/, '<br />') %> doesn't work.

Trying <%= h @var.gsub(/\n/, '<br />').html_safe %> doesn't work and is unsafe.

Trying <%= sanitize(@var.gsub(/\n/, '<br />'), :tags => %w(br) %> WORKS.

I haven't tested this very well, but it allows the BR tag to work, and replaced a dummy script alert I added with white space, so it seems to be doing its job. If anyone else has an idea or can say if this is a safe solution, please do.

Update:

Another idea suggested by Jose Valim:

<%= h(@var).gsub(/\n/, '<br />') %> Works

like image 45
Scott Swezey Avatar answered Nov 19 '22 11:11

Scott Swezey


Here's what I did:

module ApplicationHelper
  def nl2br s
    sanitize(s, tags: []).gsub(/\n/, '<br>').html_safe
  end
end
like image 1
x-yuri Avatar answered Nov 19 '22 12:11

x-yuri