session.rb 4.9 KB

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