Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class UploadsController < ApplicationController
- def finalize
- @file = StoredFile.find(params[:file])
- @file.upload_done!
- end
- def authorize
- authorize_write_to_s3 do |stored_file, errors|
- success = stored_file.save
- errors = []
- unless success
- errors += stored_file.errors.full_messages
- end
- [success, errors]
- end
- end
- protected
- def authorize_write_to_s3(https = false)
- raise "no block given" unless block_given?
- bucket = S3Config.bucket
- access_key_id = S3Config.access_key_id
- acl = S3Config.acl
- content_type = params[:content_type].to_s
- file_size = params[:file_size].to_i
- unchecked_key = params[:file_name].to_s
- stored_file = StoredFile.new do |file|
- file.easy_setup(unchecked_key, content_type)
- file.size = file_size
- end
- success, errors = yield stored_file
- if success
- content_type = stored_file.content_type
- full_key = stored_file.base_path
- expiration_date = 2.hours.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')
- # ['starts-with', '$Filename', ''],
- policy = Base64.encode64(
- "{
- 'expiration': '#{expiration_date}',
- 'conditions': [
- {'bucket': '#{bucket}'},
- {'key': '#{full_key}'},
- {'acl': '#{acl}'},
- {'Content-Type': '#{content_type}'},
- {'success_action_status': '201'},
- ['content-length-range', #{file_size}, #{file_size}],
- ['starts-with', '$filename', ''],
- ]
- }").gsub(/\n|\r/, '')
- signature = self.sign(policy, S3Config.secret_access_key)
- full_url = "#{https ? 'https' : 'http'}://#{S3Config.server}/"
- respond_to do |wants|
- wants.json do
- render :json => {
- :ok => true,
- :url => full_url,
- :file => stored_file.id.to_s,
- :headers => [],
- :params => ActiveSupport::OrderedHash[*([
- ["key", full_key],
- ["AWSAccessKeyId", access_key_id],
- ["acl", acl],
- ["Content-Type", content_type],
- ["success_action_status", "201"],
- ["policy", policy],
- ["signature", signature],
- ["Filename", ""]
- ].flatten)]
- }
- end
- end
- else
- errors = [errors] unless errors.is_a? Array
- errors = ["Unknown Error"] if errors.blank?
- respond_to do |wants|
- wants.json do
- render :json => {
- :ok => false,
- :alerts => errors
- }
- end
- end
- end
- end
- def sign(message, secret)
- raise 'missing secret' unless secret
- hmac = HMAC::SHA1.new(secret)
- hmac.update(message)
- hmaced = hmac.digest.to_s
- Base64.encode64(hmaced).chomp.gsub(/\n/,'')
- end
- end
Add Comment
Please, Sign In to add comment