Class: UriSigner::Signer

Inherits:
Object
  • Object
show all
Defined in:
lib/uri_signer/signer.rb

Overview

This is the object that wraps the other building blocks and can be used to sign requests.

Examples:

http_method = "get"
uri         = "https://api.example.com/core/people.json?page=5&per_page=25&order=name:desc&select=id,name"
secret      = "my_secret"

signer = UriSigner::Signer.new(http_method, uri, secret)

signer.http_method
# => "GET"

signer.uri
# => "https://api.example.com/core/people.json?page=5&per_page=25&order=name:desc&select=id,name"

signer.signature
# => "1AaJvChjz%2BZYJKxWsUQWNK1a%2BeGjpCs6uwQKwPw1%2FV8%3D"

signer.uri_with_signature
# => "https://api.example.com/core/people.json?_signature=6G4xiABih7FGvjwB1JsYXoeETtBCOdshIu93X1hltzk%3D"

signer.valid?("1AaJvChjz%2BZYJKxWsUQWNK1a%2BeGjpCs6uwQKwPw1%2FV8%3D")
# => true

signer.valid?('1234')
# => false

Instance Method Summary collapse

Constructor Details

#initialize(http_method, uri, secret) ⇒ void

Create a new UriSigner instance

Parameters:

  • http_method (String)

    The HTTP method used to make the request (GET, POST, PUT, and DELETE)

  • uri (String)

    The requested URI

  • secret (String)

    The secret that is used to sign the request

Raises:



37
38
39
40
41
42
43
44
45
# File 'lib/uri_signer/signer.rb', line 37

def initialize(http_method, uri, secret)
  @http_method = http_method
  @uri         = uri
  @secret      = secret

  raise UriSigner::Errors::MissingHttpMethodError.new("Please provide an HTTP method") unless http_method?
  raise UriSigner::Errors::MissingUriError.new("Please provide a URI") unless uri?
  raise UriSigner::Errors::MissingSecretError.new("Please provide a secret to sign the string") unless secret?
end

Instance Method Details

#http_methodString

Returns the uppercased HTTP Method

Returns:



66
67
68
# File 'lib/uri_signer/signer.rb', line 66

def http_method
  @http_method.to_s.upcase
end

#signatureString

Returns the signature

Returns:



73
74
75
# File 'lib/uri_signer/signer.rb', line 73

def signature
  uri_signature.signature
end

#uriString

Returns the URI passed into the constructor

Returns:



50
51
52
# File 'lib/uri_signer/signer.rb', line 50

def uri
  @uri
end

#uri_with_signatureObject

Returns the URI with the signature appended to the query string

return [String]



57
58
59
60
61
# File 'lib/uri_signer/signer.rb', line 57

def uri_with_signature
  separator = if request_parser.query_params? then '&' else '?' end
  encoded_signature = signature.extend(UriSigner::Helpers::String).escaped
  "%s%s_signature=%s" % [self.uri, separator, encoded_signature]
end

#valid?(other) ⇒ Bool

Returns true if other matches the proper signature

Returns:

  • (Bool)


80
81
82
# File 'lib/uri_signer/signer.rb', line 80

def valid?(other)
  self.signature === other
end