user3631047
user3631047

Reputation: 3384

How to safely save/retrieve HTML tags to database in rails?

I need to safely save/retrieve HTML tags to a database in my rails app. Currently I save HTML without any validation like below:

<h2>Sample title</h2> 
<p>sample description</p>

and in the view I use <%=raw @page.desription %>. It works as expected. But I need to know if it is safe or not?

Upvotes: 5

Views: 4990

Answers (2)

Edd Morgan
Edd Morgan

Reputation: 2923

You can never be sure it is safe. Always treat all user input as hostile.

However, if by "safe" you mean "devoid of potentially really harmful elements like <script>s and <style>s", then I present to you the Sanitization Helper. You can print your HTML from the database and only allow a certain whitelist of tags.

<%=raw sanitize @page.description, tags: %w(h2 p strong em a), attributes: %w(id class href) %>

The above example will allow all h2, p, strong, em and a tags, and only the id, class and href attributes on them. Everything else will be removed.

Upvotes: 11

Cereal
Cereal

Reputation: 3839

It's safe as long as it's from a trusted source, otherwise you won't know what it is they're storing exactly. So if you're the only person storing it, go for it.

Upvotes: 0

Related Questions