Module: SignedRequest

Defined in:
lib/signed_request.rb

Constant Summary collapse

STRIP_PARAMS =
['action', 'controller', 'format']

Class Method Summary collapse

Class Method Details

.sign(params, secret_key, options = {}) ⇒ Object

Sign a request on the sending end.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/signed_request.rb', line 9

def self.sign(params, secret_key, options = {})
  params = params.dup

  # Flatten any sub-hashes to a single string.
  params.keys.each do |key|
    if params[key].is_a?(Hash)
      params[key] = params[key].sort_by { |k, v| k.to_s.downcase }.to_s
    end
  end

  query   = params.sort_by { |k,v| k.to_s.downcase }
  string_to_sign = options[:path].to_s + query.to_s

  digest  = OpenSSL::Digest::Digest.new('sha1')
  hmac    = OpenSSL::HMAC.digest(digest, secret_key, string_to_sign)
  encoded = Base64.encode64(hmac).chomp
end

.validate(params, secret_key, sign_options = {}) ⇒ Object

Validate an incoming request on the receiving end.



28
29
30
31
32
33
34
35
# File 'lib/signed_request.rb', line 28

def self.validate(params, secret_key, sign_options = {})
  signature = params.delete('signature') || params.delete(:signature)
  return false if !signature

  strip_keys_from!(params, *STRIP_PARAMS)
  actual_signature = sign(params, secret_key, sign_options)
  actual_signature == signature
end