Class: ImageVise::ImageRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/image_vise/image_request.rb

Defined Under Namespace

Classes: InvalidRequest, MissingParameter, SignatureError, URLError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_params(qs_params:, secrets:) ⇒ Object

Initializes a new ParamsChecker from given HTTP server framework params. The params can be symbol- or string-keyed, does not matter.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/image_vise/image_request.rb', line 11

def self.from_params(qs_params:, secrets:)
  base64_encoded_params = qs_params.fetch(:q) rescue qs_params.fetch('q')
  given_signature = qs_params.fetch(:sig) rescue qs_params.fetch('sig')

  # Unmask slashes and equals signs (if they are present)
  base64_encoded_params = base64_encoded_params.tr('-', '/').tr('_', '+')

  # Check the signature before decoding JSON (since we will be creating symbols)
  unless valid_signature?(base64_encoded_params, given_signature, secrets)
    raise SignatureError, "Invalid or missing signature"
  end

  # Decode the JSON
  # (only AFTER the signature has been validated, so we can use symbol keys)
  decoded_json = Base64.decode64(base64_encoded_params)
  params = JSON.parse(decoded_json, symbolize_names: true)

  # Pick up the URL and validate it
  source_url_str = params.fetch(:src_url).to_s
  raise URLError, "the :src_url parameter must be non-empty" if source_url_str.empty?
  pipeline_definition = params.fetch(:pipeline)
  new(src_url: URI(source_url_str), pipeline: ImageVise::Pipeline.from_param(pipeline_definition))
rescue KeyError => e
  raise InvalidRequest.new(e.message)
end

Instance Method Details

#cache_etagObject



53
54
55
# File 'lib/image_vise/image_request.rb', line 53

def cache_etag
  Digest::SHA1.hexdigest(JSON.dump(to_h))
end

#to_hObject



49
50
51
# File 'lib/image_vise/image_request.rb', line 49

def to_h
  {pipeline: pipeline.to_params, src_url: src_url.to_s}
end

#to_path_params(signed_with_secret) ⇒ Object



37
38
39
40
41
# File 'lib/image_vise/image_request.rb', line 37

def to_path_params(signed_with_secret)
  qs = to_query_string_params(signed_with_secret)
  q_masked = qs.fetch(:q).tr('/', '-').tr('+', '_')
  '/%s/%s' % [q_masked, qs[:sig]]
end

#to_query_string_params(signed_with_secret) ⇒ Object



43
44
45
46
47
# File 'lib/image_vise/image_request.rb', line 43

def to_query_string_params(signed_with_secret)
  payload = JSON.dump(to_h)
  base64_enc = Base64.strict_encode64(payload).gsub(/\=+$/, '')
  {q: base64_enc, sig: OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, signed_with_secret, base64_enc)}
end