Created
September 7, 2016 22:21
-
-
Save johnhamelink/9294058bc2590781ee59e132b4dea37f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class S3Service | |
# TODO: Retrieve Temporary credentials from AWS metadata server (MDS) using the AWS SDK | |
# TODO: Add the x-amz-security-token to the policy, so that we can verify the temporary credentials. See here: | |
# - http://docs.aws.amazon.com/AWSSdkDocsRuby/latest/DeveloperGuide/ruby-dg-roles.html | |
# - http://www.spacevatican.org/2013/7/7/direct-to-s3-browser-uploads/ | |
def initialize(args = {}) | |
fail ArgumentError unless args[:name] && args[:type] | |
@expires = 5.minutes.from_now.iso8601 | |
@access_key_id = ENV['AWS_ACCESS_KEY_ID'] | |
@secret_access_key = ENV['AWS_SECRET_ACCESS_KEY'] | |
@bucket = ENV['AWS_S3_UPLOAD_BUCKET'] | |
@file_name = args[:name] | |
@content_type = args[:type] | |
end | |
def to_h | |
{ | |
bucket: @bucket, | |
key: "uploads/#{@file_name}", | |
acl: 'public-read', | |
'Content-Type': @content_type, | |
policy: policy, | |
signature: signature, | |
expires: @expires, | |
access_key_id: @access_key_id | |
} | |
end | |
private | |
def signature | |
Base64.strict_encode64( | |
OpenSSL::HMAC.digest( | |
OpenSSL::Digest.new('sha1'), | |
@secret_access_key, policy) | |
).strip | |
end | |
def policy | |
payload = { | |
expiration: @expires, | |
conditions: [ | |
{ bucket: @bucket }, | |
{ acl: 'public-read' }, | |
['starts-with', '$key', 'uploads/'], | |
['content-length-range', 0, 524_288_000] | |
] | |
}.to_json | |
Base64.strict_encode64(payload) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment