session.rb 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 :domain, :token, :name, :extra
  10. attr_reader :api_version
  11. alias_method :url, :domain
  12. class << self
  13. def setup(params)
  14. params.each { |k,value| public_send("#{k}=", value) }
  15. end
  16. def temp(domain:, token:, api_version: ShopifyAPI::Base.api_version, &block)
  17. session = new(domain: domain, token: token, api_version: api_version)
  18. with_session(session, &block)
  19. end
  20. def with_session(session, &_block)
  21. original_session = extract_current_session
  22. original_user = ShopifyAPI::Base.user
  23. original_password = ShopifyAPI::Base.password
  24. begin
  25. ShopifyAPI::Base.clear_session
  26. ShopifyAPI::Base.activate_session(session)
  27. yield
  28. ensure
  29. ShopifyAPI::Base.activate_session(original_session)
  30. ShopifyAPI::Base.user = original_user
  31. ShopifyAPI::Base.password = original_password
  32. end
  33. end
  34. def with_version(api_version, &block)
  35. original_session = extract_current_session
  36. session = new(domain: original_session.site, token: original_session.token, api_version: api_version)
  37. with_session(session, &block)
  38. end
  39. def prepare_domain(domain)
  40. return nil if domain.blank?
  41. # remove http:// or https://
  42. domain = domain.strip.gsub(%r{\Ahttps?://}, '')
  43. # extract host, removing any username, password or path
  44. shop = URI.parse("https://#{domain}").host
  45. # extract subdomain of .myshopify.com
  46. if (idx = shop.index("."))
  47. shop = shop.slice(0, idx)
  48. end
  49. return nil if shop.empty?
  50. "#{shop}.#{myshopify_domain}"
  51. rescue URI::InvalidURIError
  52. nil
  53. end
  54. def validate_signature(params)
  55. params = (params.respond_to?(:to_unsafe_hash) ? params.to_unsafe_hash : params).with_indifferent_access
  56. return false unless (signature = params[:hmac])
  57. calculated_signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('SHA256'), secret, encoded_params_for_signature(params))
  58. Rack::Utils.secure_compare(calculated_signature, signature)
  59. end
  60. private
  61. def encoded_params_for_signature(params)
  62. params = params.except(:signature, :hmac, :action, :controller)
  63. params.map{|k,v| "#{URI.escape(k.to_s, '&=%')}=#{URI.escape(v.to_s, '&%')}"}.sort.join('&')
  64. end
  65. def extract_current_session
  66. site = ShopifyAPI::Base.site.to_s
  67. token = ShopifyAPI::Base.headers['X-Shopify-Access-Token']
  68. version = ShopifyAPI::Base.api_version
  69. new(domain: site, token: token, api_version: version)
  70. end
  71. end
  72. def initialize(domain:, token:, api_version: ShopifyAPI::Base.api_version, extra: {})
  73. self.domain = self.class.prepare_domain(domain)
  74. self.api_version = api_version
  75. self.token = token
  76. self.extra = extra
  77. end
  78. def create_permission_url(scope, redirect_uri, options = {})
  79. params = { client_id: api_key, scope: scope.join(','), redirect_uri: redirect_uri }
  80. params[:state] = options[:state] if options[:state]
  81. construct_oauth_url("authorize", params)
  82. end
  83. def request_token(params)
  84. return token if token
  85. unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i
  86. raise ShopifyAPI::ValidationException, "Invalid Signature: Possible malicious login"
  87. end
  88. response = access_token_request(params[:code])
  89. if response.code == "200"
  90. self.extra = JSON.parse(response.body)
  91. self.token = extra.delete('access_token')
  92. if (expires_in = extra.delete('expires_in'))
  93. extra['expires_at'] = Time.now.utc.to_i + expires_in
  94. end
  95. token
  96. else
  97. raise RuntimeError, response.msg
  98. end
  99. end
  100. def shop
  101. Shop.current
  102. end
  103. def site
  104. "https://#{domain}"
  105. end
  106. def api_version=(version)
  107. @api_version = ApiVersion::NullVersion.matches?(version) ? ApiVersion::NullVersion : ApiVersion.find_version(version)
  108. end
  109. def valid?
  110. domain.present? && token.present? && api_version.is_a?(ApiVersion)
  111. end
  112. def expires_in
  113. return unless expires_at.present?
  114. [0, expires_at.to_i - Time.now.utc.to_i].max
  115. end
  116. def expires_at
  117. return unless extra.present?
  118. @expires_at ||= Time.at(extra['expires_at']).utc
  119. end
  120. def expired?
  121. return false if expires_in.nil?
  122. expires_in <= 0
  123. end
  124. def hash
  125. state.hash
  126. end
  127. def ==(other)
  128. self.class == other.class && state == other.state
  129. end
  130. alias_method :eql?, :==
  131. protected
  132. def state
  133. [domain, token, api_version, extra]
  134. end
  135. private
  136. def parameterize(params)
  137. URI.escape(params.collect { |k, v| "#{k}=#{v}" }.join('&'))
  138. end
  139. def access_token_request(code)
  140. uri = URI.parse(construct_oauth_url('access_token'))
  141. https = Net::HTTP.new(uri.host, uri.port)
  142. https.use_ssl = true
  143. request = Net::HTTP::Post.new(uri.request_uri)
  144. request.set_form_data('client_id' => api_key, 'client_secret' => secret, 'code' => code)
  145. https.request(request)
  146. end
  147. def construct_oauth_url(path, query_params = {})
  148. query_string = "?#{parameterize(query_params)}" unless query_params.empty?
  149. "https://#{domain}/admin/oauth/#{path}#{query_string}"
  150. end
  151. end
  152. end