Hashing

Prateek Vasireddy edited this page Apr 30, 2016 · 10 revisions

Purpose

To secure your attachments by hiding the actual directory structure from prying eyes.

Configure Paperclip Defaults

Paperclip does not use hashing when generating attachment paths, by default:

# Highlighting default options related 
# to path/url generation and hashing

Paperclip::Attachment.default_options
# => {
#     :hash_data=>":class/:attachment/:id/:style/:updated_at",
#     :hash_digest=>"SHA1",
#     :path=>":rails_root/public:url",
#     :url=>"/system/:class/:attachment/:id_partition/:style/:filename",
#    }

Add an initializer to modify this behavior:

# config/initializers/paperclip_defaults.rb

Paperclip::Attachment.default_options.update({
  url: "/system/:class/:attachment/:id_partition/:style/:hash.:extension",
  hash_secret: Rails.application.secrets.secret_key_base
})

This path depends on ruby :path=>":rails_root/public:url" , as specified in the default_options.

Adding the :hash interpolation to the path patters injects a hash generated from the :hash_secret and :hash_data options.

Generate a :hash_secret using SecureRandom.base64(128) from a rails console to generate a relatively secure random string.

Once you've got that set up, defining attachments requires no modifications to get the new hashing behavior (except perhaps restarting your development server):

class Profile
  has_attached_file :portrait
end
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.