wynst

easy should be easier

Paperclip: IE7 Mixed-content Issue

On upgrading a web application to use ssl/https all over the site, our users encounter mixed-content issue when using Internet Explorer. (google link)

ie. Internet Explorer browser nags the User with a warning dialog, because our site url is https:// but we display an image that use http:// protocol.

We’ve been using PaperclipS3UrlRewriter Rack Middleware for this issue, but seems to be failing as of lately.

Previously it also fails when we render a template via ajax. The middleware doesn’t handle text/javascript Content-Type.

To solve this once and for all, we delve into paperclip docs, which brings us to the following solution:

app/models/user.rb
1
2
3
4
5
6
7
8
9
10
11
  has_attached_file :avatar,
    :storage        => :s3,
    :s3_credentials => "#{::Rails.root.to_s}/config/s3.yml",
    :s3_protocol => lambda { |style, obj|
      if Rails.env.production? || Rails.env.staging?
        "https"
      else
        "http"
      end
    },
    :s3_permissions => :public_read

Nice. mixed-content issue seemingly solved.

But follow-up issue cropped up when uploading an image, the image is not displayed in browsers.

checking….

So, Paperclip/S3 doesn’t set the file to publicly readable.

A snippet from lib/paperclip/storage/s3.rb that affect this behaviour:

ss

(github link)

solution

After checking out the code, we decided to remove PaperclipS3UrlRewriter middleware, discard the paperclip changes, and just replace (manually..) all calls to:

app/views/users/_mini_profile.haml
1
image_tag(user.avatar.url(:mini))

to the following code:

all templates that use s3 image/assets
1
s3_image_tag(user.avatar.url(:mini))
app/helpers/application_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
  # generate https url if applicable
  def apply_secure_url_from(url, options={})
    if request.ssl? && url.starts_with?('http://')
      url.gsub(/^http/, 'https')
    else
      url
    end
  end

  # shortcut for modifying image_tag
  def s3_image_tag(source, options={})
    image_tag(apply_secure_url_from(source), options)
  end

Comments