Skip to content

Commit

Permalink
Add signature config
Browse files Browse the repository at this point in the history
  • Loading branch information
janklimo committed Jun 12, 2020
1 parent 5ff6f09 commit 15b0bde
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 6 deletions.
25 changes: 22 additions & 3 deletions lib/cloudimage/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ module Cloudimage
class InvalidConfig < StandardError; end

class Client
attr_reader :token
attr_reader :token, :salt, :signature_length

API_VERSION = 'v7'
DEFAULT_SIGNATURE_LENGTH = 20

def initialize(token: nil)
def initialize(
token: nil,
salt: nil,
signature_length: DEFAULT_SIGNATURE_LENGTH
)
@token = token
@salt = salt
@signature_length = signature_length

ensure_valid_config
end
Expand All @@ -27,9 +34,21 @@ def base_url_for(token)
end

def ensure_valid_config
return unless token.to_s.strip.empty?
ensure_valid_token
ensure_valid_signature_length
end

def ensure_valid_token
return unless token.nil?

raise InvalidConfig, 'Please specify your Cloudimage customer token.'
end

def ensure_valid_signature_length
return if salt.nil?
return if (6..40).cover? signature_length

raise InvalidConfig, 'Signature length must be must be 6-40 characters.'
end
end
end
16 changes: 13 additions & 3 deletions lib/cloudimage/uri.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'digest'

require_relative 'params'
require_relative 'custom_helpers'

Expand Down Expand Up @@ -32,14 +34,22 @@ def initialize(base_url, path)
alias_method from, to
end

def to_url(extra_params = {})
url_params = params.merge(extra_params)
uri.query_values = url_params if url_params.any?
def to_url(**extra_params)
set_uri_params(extra_params)
uri.to_s
end

private

def set_uri_params(**extra_params)
url_params = params.merge(extra_params)
uri.query_values = url_params if url_params.any?
end

def signature
Digest::SHA1.hexdigest(salt + uri.request_uri.sub('/v7', ''))
end

def ensure_path_format(path)
path.start_with?('/') ? path : "/#{path}"
end
Expand Down
13 changes: 13 additions & 0 deletions spec/cloudimage/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,18 @@
expect { described_class.new }
.to raise_error Cloudimage::InvalidConfig, /Cloudimage customer token/
end

context 'URL signatures' do
it 'has a default signature length' do
client = described_class.new(token: 'mytoken')
expect((6..40)).to cover client.signature_length
end

it 'raises an error when given an invalid signature length' do
expect do
described_class.new(token: 'token', salt: 'slt', signature_length: 5)
end.to raise_error Cloudimage::InvalidConfig, /Signature length must be/
end
end
end
end

0 comments on commit 15b0bde

Please sign in to comment.