Created
August 30, 2013 03:54
-
-
Save cwoodcox/6386184 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Policy | |
attr_reader :expires, :response | |
def initialize user | |
if user | |
@expires = 8.hours.from_now | |
content_length = 100..50.megabytes | |
user_id = user.email.split('@').reverse.join('/') | |
else | |
@expires = 30.minutes.from_now | |
content_length = 100..15.megabytes | |
user_id = "anonymous" | |
end | |
s3 = AWS::S3.new | |
bucket = s3.buckets['api.octanner.com-temp-upload'] | |
# Build a signed S3 policy & upload form | |
upload = bucket.presigned_post(expires: @expires, content_length: content_length) | |
.where(:key).starts_with("upload/#{user_id}/") | |
.where(:acl).is("public-read") | |
.where(:content_type).starts_with("image/") | |
.where(:success_action_status).is("201") | |
.where_metadata("user-id").is(user_id) | |
# Create a JSON response explaining how to build the <form> | |
@response = { | |
action: upload.url.to_s, | |
method: 'POST', | |
type: 'multipart/form-data', | |
input: { | |
acl: 'public-read', | |
'Content-Type' => 'image/jpeg', | |
'x-amz-meta-user-id' => user_id, | |
'success_action_status' => '201', | |
key: { type: 'string', prefix: "upload/#{user_id}/" } | |
} | |
} | |
# Bring in the fields created by the policy builder | |
upload.fields.each do |name, value| | |
@response[:input][name] = value unless value.nil? | |
end | |
# And require a file | |
@response[:input][:file] = { type: 'file' } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment