Class: S3DirectUpload::UploadHelper::S3Uploader

Inherits:
Object
  • Object
show all
Defined in:
lib/s3_direct_upload/form_helper.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ S3Uploader

Returns a new instance of S3Uploader.



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/s3_direct_upload/form_helper.rb', line 13

def initialize(options)
  @additional_headers = options[:additional_headers] || []
  @options = options.reverse_merge(
    aws_access_key_id: S3DirectUpload.config.access_key_id,
    aws_secret_access_key: S3DirectUpload.config.secret_access_key,
    bucket: S3DirectUpload.config.bucket,
    acl: "public-read",
    expiration: 10.hours.from_now.utc.iso8601,
    max_file_size: 64.gigabytes,
    as: "file",
    key: key
  )
end

Instance Method Details

#fieldsObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/s3_direct_upload/form_helper.rb', line 41

def fields
  fields = {
    :key => @options[:key] || key,
    :acl => @options[:acl],
    :policy => policy,
    :signature => signature,
    "AWSAccessKeyId" => @options[:aws_access_key_id],
    success_action_status: "201"
  }
  @additional_headers.each do |header|
    fields[header[0]]=header[1]
  end
  fields
end

#form_optionsObject



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/s3_direct_upload/form_helper.rb', line 27

def form_options
  {
    id: @options[:id],
    class: @options[:class],
    method: "post",
    authenticity_token: false,
    multipart: true,
    data: {
      post: @options[:post],
      as: @options[:as]
    }.reverse_merge(@options[:data] || {})
  }
end

#keyObject



56
57
58
# File 'lib/s3_direct_upload/form_helper.rb', line 56

def key
  @key ||= "uploads/#{SecureRandom.hex}/${filename}"
end

#policyObject



64
65
66
# File 'lib/s3_direct_upload/form_helper.rb', line 64

def policy
  Base64.encode64(policy_data.to_json).gsub("\n", "")
end

#policy_dataObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/s3_direct_upload/form_helper.rb', line 68

def policy_data
  header_conditions = @additional_headers.map { |header| { header[0] => header[1] } }
  conditions = [
      ["starts-with", "$utf8", ""],
      ["starts-with", "$key", ""],
      ["content-length-range", 0, @options[:max_file_size]],
      ["starts-with","$Content-Type",""],
      {bucket: @options[:bucket]},
      {acl: @options[:acl]},
      {success_action_status: "201"}
    ].concat(header_conditions)
  {
    expiration: @options[:expiration],
    conditions: conditions 
  }
end

#signatureObject



85
86
87
88
89
90
91
92
# File 'lib/s3_direct_upload/form_helper.rb', line 85

def signature
  Base64.encode64(
    OpenSSL::HMAC.digest(
      OpenSSL::Digest::Digest.new('sha1'),
      @options[:aws_secret_access_key], policy
    )
  ).gsub("\n", "")
end

#urlObject



60
61
62
# File 'lib/s3_direct_upload/form_helper.rb', line 60

def url
  "https://s3.amazonaws.com/#{@options[:bucket]}/"
end