module Sinatra::Shopified

This Gem's module namespace

Constants

VERSION

Gem version

Public Class Methods

registered(app) click to toggle source

Register the module with Sinatra @param [Object] app the Sinatra App

# File lib/sinatra/shopified.rb, line 14
def self.registered(app)
  # Register the helpers for this Gem
  app.helpers Shopified::Helpers
  
  # Disable iFrame protection (for ESDK)
  app.set :protection, except: :frame_options
  
  # Setup Shopify session with the app's credentials
  ShopifyAPI::Session.setup(api_key: ENV['SHOPIFY_API_KEY'], secret: ENV['SHOPIFY_API_SECRET'])
  
  # Auth controller which handles creating shop sessions,
  # hanlding app permissions, and more
  app.get '/auth' do
    # Setup our session
    session[:shopify_domain] = params[:shop] if params.key?('shop')
    api_session = ShopifyAPI::Session.new session[:shopify_domain]

    if params.key? 'code'
      # Create the shop if its new, update the token, and activate the session
      Models::Shop.create(shop: session[:shopify_domain]) unless current_shop

      # Sinatra 2 issue
      params.delete('captures') if params.key?('captures')
      
      current_shop.update_attribute :token, api_session.request_token(params)
      shopify_session_activate
      
      redirect to(ENV['SHOPIFY_APP_REDIRECT_AFTER_AUTH'])
    else
      # No code, lets ask for app permissions
      redirect api_session.create_permission_url(ENV['SHOPIFY_API_SCOPE'].split(','), to('/auth', true))
    end
  end
  
  # Catch ant UnauthrorizedAccess from Shopify and redirect to auth
  app.error ActiveResource::UnauthorizedAccess do
    params[:shop] = session[:shopify_domain] if session[:shopify_domain]
    authorize_shop_fallback
  end
end