session.rb 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. require 'openssl'
  2. require 'rack'
  3. module ShopifyAPI
  4. class ValidationException < StandardError
  5. end
  6. class Session
  7. cattr_accessor :api_key, :secret, :protocol, :myshopify_domain, :port
  8. self.protocol = 'https'
  9. self.myshopify_domain = 'myshopify.com'
  10. attr_accessor :url, :token, :name, :extra
  11. class << self
  12. def setup(params)
  13. params.each { |k,value| public_send("#{k}=", value) }
  14. end
  15. def temp(domain, token, &block)
  16. session = new(domain, token)
  17. original_site = ShopifyAPI::Base.site.to_s
  18. original_token = ShopifyAPI::Base.headers['X-Shopify-Access-Token']
  19. original_session = new(original_site, original_token)
  20. begin
  21. ShopifyAPI::Base.activate_session(session)
  22. yield
  23. ensure
  24. ShopifyAPI::Base.activate_session(original_session)
  25. end
  26. end
  27. def prepare_url(url)
  28. return nil if url.blank?
  29. # remove http:// or https://
  30. url = url.strip.gsub(/\Ahttps?:\/\//, '')
  31. # extract host, removing any username, password or path
  32. shop = URI.parse("https://#{url}").host
  33. # extract subdomain of .myshopify.com
  34. if idx = shop.index(".")
  35. shop = shop.slice(0, idx)
  36. end
  37. return nil if shop.empty?
  38. shop = "#{shop}.#{myshopify_domain}"
  39. port ? "#{shop}:#{port}" : shop
  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, extra = {})
  56. self.url = self.class.prepare_url(url)
  57. self.token = token
  58. self.extra = extra
  59. end
  60. def create_permission_url(scope, redirect_uri = nil)
  61. params = {:client_id => api_key, :scope => scope.join(',')}
  62. params[:redirect_uri] = redirect_uri if redirect_uri
  63. "#{site}/oauth/authorize?#{parameterize(params)}"
  64. end
  65. def request_token(params)
  66. return token if token
  67. unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i
  68. raise ShopifyAPI::ValidationException, "Invalid Signature: Possible malicious login"
  69. end
  70. response = access_token_request(params['code'])
  71. if response.code == "200"
  72. self.extra = JSON.parse(response.body)
  73. self.token = extra.delete('access_token')
  74. if expires_in = extra.delete('expires_in')
  75. extra['expires_at'] = Time.now.utc.to_i + expires_in
  76. end
  77. token
  78. else
  79. raise RuntimeError, response.msg
  80. end
  81. end
  82. def shop
  83. Shop.current
  84. end
  85. def site
  86. "#{protocol}://#{url}/admin"
  87. end
  88. def valid?
  89. url.present? && token.present?
  90. end
  91. def expires_in
  92. return unless expires_at.present?
  93. [0, expires_at.to_i - Time.now.utc.to_i].max
  94. end
  95. def expires_at
  96. return unless extra.present?
  97. @expires_at ||= Time.at(extra['expires_at']).utc
  98. end
  99. def expired?
  100. return false if expires_in.nil?
  101. expires_in <= 0
  102. end
  103. private
  104. def parameterize(params)
  105. URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))
  106. end
  107. def access_token_request(code)
  108. uri = URI.parse("#{protocol}://#{url}/admin/oauth/access_token")
  109. https = Net::HTTP.new(uri.host, uri.port)
  110. https.use_ssl = true
  111. request = Net::HTTP::Post.new(uri.request_uri)
  112. request.set_form_data({"client_id" => api_key, "client_secret" => secret, "code" => code})
  113. https.request(request)
  114. end
  115. end
  116. end