Sha256: 82b720f1b3ced9b32aa64a074418ec862bb0b9f4edacf6895a402ca37b54673d

Contents?: true

Size: 1.05 KB

Versions: 13

Compression:

Stored size: 1.05 KB

Contents

module AppleNews
  class Security
    attr_accessor :method, :url, :content_type, :content_body

    def initialize(method, url)
      @config = AppleNews.config

      @method = method.upcase
      @url = url
      @date = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
      @content_type = nil
      @content_body = nil
    end

    def authorization
      if @method == 'POST' && (@content_type.nil? || @content_body.nil?)
        raise "POST requests require the content type and body to be included in the signature generation"
      end

      "HHMAC; key=#{@config.api_key_id}; signature=#{signature}; date=#{@date}"
    end

    private

    def hash_content
      [@method, @url, @date, @content_type, @content_body].compact
    end

    def canonical_request
      hash_content.join('')
    end

    def key
      Base64.strict_decode64(@config.api_key_secret)
    end

    def digest
      sha256 = OpenSSL::Digest.new('sha256')
      OpenSSL::HMAC.digest(sha256, key, canonical_request)
    end

    def signature
      Base64.strict_encode64(digest)
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
apple-news-0.4.2 lib/apple-news/security.rb
apple-news-0.4.1 lib/apple-news/security.rb
apple-news-0.4.0 lib/apple-news/security.rb
apple-news-0.3.1 lib/apple-news/security.rb
apple-news-0.3.0 lib/apple-news/security.rb
apple-news-0.2.5 lib/apple-news/security.rb
apple-news-0.2.4 lib/apple-news/security.rb
apple-news-0.2.3 lib/apple-news/security.rb
apple-news-0.2.2 lib/apple-news/security.rb
apple-news-0.2.1 lib/apple-news/security.rb
apple-news-0.2.0 lib/apple-news/security.rb
apple-news-0.1.1 lib/apple-news/security.rb
apple-news-0.1.0 lib/apple-news/security.rb