Skip to content

Instantly share code, notes, and snippets.

@8parth
Created November 1, 2018 04:49
Show Gist options
  • Save 8parth/3bf9b4fef2af2431bab3a7ab1203f169 to your computer and use it in GitHub Desktop.
Save 8parth/3bf9b4fef2af2431bab3a7ab1203f169 to your computer and use it in GitHub Desktop.
Paperclip Extension that provides `cloudfront_signed_url` method. The extension supports all options and styles that can be passed to `url` method of paperclip.
# frozen_string_literal: true
# lib/paperclip/cloudfront_signed_url_extension
module Paperclip
module CloudfrontSignedUrlExtension
include UriValidationHelper
def cloudfront_signed_url(time = nil, style_name = default_style, options = {})
return url(style_name, options) unless valid_url?(url(style_name))
options_h =
if time.present?
{ expires: Time.zone.now + time }
else
{}
end
options_h.merge(options)
begin
Aws::CF::Signer.sign_url(url(style_name), options_h)
rescue => e
Rails.logger.error("cloudfront_signed_url raised: #{e.message}")
url(style_name)
end
end
end
end
# frozen_string_literal: true
# lib/uri_validation_helper.rb
module UriValidationHelper
def valid_url?(url)
return false if url.blank?
begin
parsed_uri = URI.parse(url)
parsed_uri.is_a?(URI::HTTP) || parsed_uri.is_a?(URI::HTTPS)
rescue URI::Error
return false
end
end
def valid_cloudfront_url?(url)
return false if url.blank?
begin
parsed_uri = URI.parse(url)
(parsed_uri.is_a?(URI::HTTP) || parsed_uri.is_a?(URI::HTTPS)) && parsed_uri.host.include?('cloudfront.net')
rescue URI::Error
return false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment