session.rb 4.6 KB

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