Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Escaping HTML using the h() AND excluding specific tags

I was wondering, and was as of yet, unable to find any answers online, how to accomplish the following.

Let's say I have a string that contains the following:

my_string = "Hello, I am a string." (in the preview window I see that this is actually formatting in BOLD and ITALIC instead of showing the "strong" and "i" tags)

Now, I would like to make this secure, using the html_escape() (or h()) method/function. So I'd like to prevent users from inserting any javascript and/or stylesheets, however, I do still want to have the word "Hello" shown in bold, and the word "string" shown in italic.

As far as I can see, the h() method does not take any additional arguments, other than the piece of text itself.

Is there a way to escape only certain html tags, instead of all? Like either White or Black listing tags?

Example of what this might look like, of what I'm trying to say would be:

h(my_string, :except => [:strong, :i]) # => so basically, escape everything, but leave "strong" and "i" tags alone, do not escape these.

Is there any method or way I could accomplish this?

Thanks in advance!

like image 644
Meskyanichi Avatar asked Sep 29 '09 20:09

Meskyanichi


2 Answers

Excluding specific tags is actually pretty hard problem. Especially the script tag can be inserted in very many different ways - detecting them all is very tricky.

If at all possible, don't implement this yourself.

like image 189
hrnt Avatar answered Sep 24 '22 17:09

hrnt


Use the white list plugin or a modified version of it . It's superp! You can have a look Sanitize as well(Seems better, never tried it though).

like image 33
khelll Avatar answered Sep 23 '22 17:09

khelll