session.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. module ShopifyAPI
  2. class Session
  3. cattr_accessor :api_key
  4. cattr_accessor :secret
  5. cattr_accessor :protocol
  6. self.protocol = 'https'
  7. attr_accessor :url, :token, :name
  8. class << self
  9. def setup(params)
  10. params.each { |k,value| send("#{k}=", value) }
  11. end
  12. def temp(domain, token, &block)
  13. session = new(domain, token)
  14. begin
  15. original_domain = host_with_port(ShopifyAPI::Base.site.to_s)
  16. rescue URI::InvalidURIError
  17. end
  18. original_token = ShopifyAPI::Base.headers['X-Shopify-Access-Token']
  19. original_session = new(original_domain, 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. url.gsub!(/https?:\/\//, '') # remove http:// or https://
  30. url.concat(".myshopify.com") unless url.include?('.') # extend url to myshopify.com if no host is given
  31. end
  32. def validate_signature(params)
  33. return false unless signature = params[:signature]
  34. sorted_params = params.except(:signature, :action, :controller).collect{|k,v|"#{k}=#{v}"}.sort.join
  35. Digest::MD5.hexdigest(secret + sorted_params) == signature
  36. end
  37. def host_with_port(site)
  38. parsed_site = URI.parse(site)
  39. host = parsed_site.host or return
  40. port = parsed_site.port
  41. if (protocol == 'http' && port == 80) || (protocol == 'https' && port == 443)
  42. host
  43. else
  44. "#{host}:#{port}"
  45. end
  46. end
  47. end
  48. def initialize(url, token = nil, params = nil)
  49. self.url, self.token = url, token
  50. self.class.prepare_url(self.url)
  51. if params
  52. unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i
  53. raise "Invalid Signature: Possible malicious login"
  54. end
  55. end
  56. end
  57. def shop
  58. Shop.current
  59. end
  60. def site
  61. "#{protocol}://#{url}/admin"
  62. end
  63. def valid?
  64. url.present? && token.present?
  65. end
  66. end
  67. end