session.rb 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. require 'openssl'
  2. require 'rack'
  3. module ShopifyAPI
  4. class ValidationException < StandardError
  5. end
  6. class Session
  7. cattr_accessor :api_key, :secret, :myshopify_domain
  8. self.myshopify_domain = 'myshopify.com'
  9. attr_accessor :url, :token, :name, :extra
  10. attr_reader :api_version
  11. class << self
  12. def setup(params)
  13. params.each { |k,value| public_send("#{k}=", value) }
  14. end
  15. def temp(domain, token, api_version = :no_version, &_block)
  16. session = new(domain, token, api_version)
  17. original_site = ShopifyAPI::Base.site.to_s
  18. original_token = ShopifyAPI::Base.headers['X-Shopify-Access-Token']
  19. original_version = ShopifyAPI::Base.api_version
  20. original_session = new(original_site, original_token, original_version)
  21. begin
  22. ShopifyAPI::Base.activate_session(session)
  23. yield
  24. ensure
  25. ShopifyAPI::Base.activate_session(original_session)
  26. end
  27. end
  28. def prepare_url(url)
  29. return nil if url.blank?
  30. # remove http:// or https://
  31. url = url.strip.gsub(/\Ahttps?:\/\//, '')
  32. # extract host, removing any username, password or path
  33. shop = URI.parse("https://#{url}").host
  34. # extract subdomain of .myshopify.com
  35. if idx = shop.index(".")
  36. shop = shop.slice(0, idx)
  37. end
  38. return nil if shop.empty?
  39. "#{shop}.#{myshopify_domain}"
  40. rescue URI::InvalidURIError
  41. nil
  42. end
  43. def validate_signature(params)
  44. params = (params.respond_to?(:to_unsafe_hash) ? params.to_unsafe_hash : params).with_indifferent_access
  45. return false unless signature = params[:hmac]
  46. calculated_signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new(), secret, encoded_params_for_signature(params))
  47. Rack::Utils.secure_compare(calculated_signature, signature)
  48. end
  49. private
  50. def encoded_params_for_signature(params)
  51. params = params.except(:signature, :hmac, :action, :controller)
  52. params.map{|k,v| "#{URI.escape(k.to_s, '&=%')}=#{URI.escape(v.to_s, '&%')}"}.sort.join('&')
  53. end
  54. end
  55. def initialize(url, token = nil, api_version = :no_version, extra = {})
  56. self.url = self.class.prepare_url(url)
  57. self.api_version = api_version
  58. self.token = token
  59. self.extra = extra
  60. end
  61. def create_permission_url(scope, redirect_uri = nil)
  62. params = {:client_id => api_key, :scope => scope.join(',')}
  63. params[:redirect_uri] = redirect_uri if redirect_uri
  64. construct_oauth_url("authorize", params)
  65. end
  66. def request_token(params)
  67. return token if token
  68. unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i
  69. raise ShopifyAPI::ValidationException, "Invalid Signature: Possible malicious login"
  70. end
  71. response = access_token_request(params['code'])
  72. if response.code == "200"
  73. self.extra = JSON.parse(response.body)
  74. self.token = extra.delete('access_token')
  75. if expires_in = extra.delete('expires_in')
  76. extra['expires_at'] = Time.now.utc.to_i + expires_in
  77. end
  78. token
  79. else
  80. raise RuntimeError, response.msg
  81. end
  82. end
  83. def shop
  84. Shop.current
  85. end
  86. def site
  87. "https://#{url}"
  88. end
  89. def api_version=(version)
  90. @api_version = ApiVersion.coerce_to_version(version)
  91. end
  92. def valid?
  93. url.present? && token.present?
  94. end
  95. def expires_in
  96. return unless expires_at.present?
  97. [0, expires_at.to_i - Time.now.utc.to_i].max
  98. end
  99. def expires_at
  100. return unless extra.present?
  101. @expires_at ||= Time.at(extra['expires_at']).utc
  102. end
  103. def expired?
  104. return false if expires_in.nil?
  105. expires_in <= 0
  106. end
  107. private
  108. def parameterize(params)
  109. URI.escape(params.collect { |k, v| "#{k}=#{v}" }.join('&'))
  110. end
  111. def access_token_request(code)
  112. uri = URI.parse(construct_oauth_url('access_token'))
  113. https = Net::HTTP.new(uri.host, uri.port)
  114. https.use_ssl = true
  115. request = Net::HTTP::Post.new(uri.request_uri)
  116. request.set_form_data('client_id' => api_key, 'client_secret' => secret, 'code' => code)
  117. https.request(request)
  118. end
  119. def construct_oauth_url(path, query_params = {})
  120. query_string = "?#{parameterize(query_params)}" unless query_params.empty?
  121. "https://#{url}/admin/oauth/#{path}#{query_string}"
  122. end
  123. end
  124. end