Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

7.7 KB
Raw Blame
class Shopify::CallbacksController < ApplicationController
  include Shopify::IntegrationHelper

  def show
    @account_id = verified_account_id
    raise StandardError, 'Shopify authorization was denied' if params[:error].present?

    if chatwoot_initiated?
      handle_chatwoot_initiated_flow
    elsif params[:code].blank?
      handle_shopify_initiated_without_code
    else
      handle_shopify_initiated_flow
    end
  rescue StandardError => e
    Rails.logger.error("Shopify callback error: #{e.message}")
    redirect_to error_redirect_url, allow_other_host: true
  end

  private

  def chatwoot_initiated? = verified_account_id.present?

  def handle_chatwoot_initiated_flow
    raise StandardError, 'Invalid state parameter' if account.blank?

    ensure_shopify_enabled!(account: account)
    raise StandardError, 'Invalid HMAC signature' unless valid_hmac?
    raise StandardError, 'Invalid shop domain' unless valid_shop_domain?

    @shopify_installation_generation = Shopify::InstallationGeneration.current(account)
    exchange_and_create_hook
    redirect_to shopify_integration_url, allow_other_host: true
  end

  def exchange_and_create_hook
    shop_generation = Shopify::PendingInstallation.generation(shop: params[:shop])
    exchange_access_token
    with_current_shop_generation(shop_generation) do
      callback_service.connect(account: account, generation: @shopify_installation_generation, credentials: parsed_body)
    end
  end

  def with_current_shop_generation(expected_generation)
    ActiveRecord::Base.transaction do
      unless expected_generation.to_i == Shopify::PendingInstallation.generation(shop: params[:shop])
        raise StandardError, 'Shopify installation changed during authorization'
      end

      yield
    end
  end

  def handle_shopify_initiated_flow
    prepare_shopify_initiated_flow
    verify_shopify_oauth_state!
    load_existing_shopify_account

    # Security: HMAC validation ensures params (including shop) haven't been tampered with.
    # Additionally, the OAuth code is cryptographically bound to the shop that issued it.
    # Shopify will reject any attempt to exchange a code at a different shop's endpoint.
    exchange_access_token

    if @account
      with_current_shop_generation(@pending_installation_generation) do
        callback_service.reconnect(account: account, generation: @shopify_installation_generation, credentials: parsed_body)
      end
      return redirect_to existing_account_redirect_url, allow_other_host: true
    end

    token_key = Shopify::PendingInstallation.create(
      access_token: parsed_body['access_token'],
      shop: params[:shop],
      scope: parsed_body['scope'],
      shop_generation: @pending_installation_generation
    )

    redirect_to "#{frontend_url}/app/auth/signup?shopify_pending_install=#{CGI.escape(token_key)}", allow_other_host: true
  end

  def handle_shopify_initiated_without_code
    prepare_shopify_initiated_flow
    load_existing_shopify_account
    hook = @account&.hooks&.find_by(app_id: 'shopify')
    return redirect_to existing_account_redirect_url, allow_other_host: true if callback_service.reusable_hook?(hook)

    state = SecureRandom.hex(16)
    Redis::SecureStorage.set(
      oauth_state_key(state),
      {
        shop: params[:shop],
        pending_installation_generation: Shopify::PendingInstallation.generation(shop: params[:shop])
      },
      10.minutes
    )

    authorization_url = oauth_client.auth_code.authorize_url(
      redirect_uri: redirect_callback_uri,
      scope: REQUIRED_SCOPES.join(','),
      state: state
    )
    redirect_to authorization_url, allow_other_host: true
  end

  def prepare_shopify_initiated_flow
    ensure_shopify_enabled!
    raise StandardError, 'Invalid HMAC signature' unless valid_hmac?
    raise StandardError, 'Invalid shop domain' unless valid_shop_domain?
  end

  def verify_shopify_oauth_state!
    state = params[:state].to_s
    raise StandardError, 'Invalid state parameter' unless state.match?(/\A[0-9a-f]{32}\z/)

    stored_state = JSON.parse(Redis::SecureStorage.get(oauth_state_key(state)).to_s)
    raise StandardError, 'Invalid state parameter' unless stored_state['shop'] == params[:shop]

    @pending_installation_generation = stored_state['pending_installation_generation']
    Redis::SecureStorage.delete(oauth_state_key(state))
    return if @pending_installation_generation.to_i == Shopify::PendingInstallation.generation(shop: params[:shop])

    raise StandardError, 'Shopify installation changed during authorization'
  rescue JSON::ParserError
    raise StandardError, 'Invalid state parameter'
  end

  def exchange_access_token
    @response = oauth_client.auth_code.get_token(params[:code], redirect_uri: redirect_callback_uri)
  end

  def load_existing_shopify_account
    @account = callback_service.existing_account
    return unless @account

    @account_id = account.id
    ensure_shopify_enabled!(account: account)
    @shopify_installation_generation = Shopify::InstallationGeneration.current(account)
  end

  def existing_account_redirect_url
    billing_identity = account.internal_attributes.stringify_keys
    return shopify_billing_url if billing_identity['billing_provider'] == 'shopify' && billing_identity['signup_source'] == 'shopify'

    shopify_integration_url
  end

  def parsed_body
    @parsed_body ||= begin
      parsed = @response.response.parsed
      # Handle both SnakyHash (production) and regular Hash (tests)
      {
        'access_token' => parsed.respond_to?(:access_token) ? parsed.access_token : parsed['access_token'],
        'scope' => parsed.respond_to?(:scope) ? parsed.scope : parsed['scope']
      }
    end
  end

  def oauth_client
    OAuth2::Client.new(
      client_id,
      client_secret,
      {
        site: "https://#{params[:shop]}",
        authorize_url: '/admin/oauth/authorize',
        token_url: '/admin/oauth/access_token'
      }
    )
  end

  def callback_service = (@callback_service ||= Shopify::CallbackService.new(shop: params[:shop]))

  def account = (@account ||= Account.find(@account_id))

  def verified_account_id
    return unless params[:state].to_s.count('.') == 2

    @verified_account_id ||= verify_shopify_token(params[:state])
  end

  def ensure_shopify_enabled!(account: nil)
    raise StandardError, 'Shopify integration is disabled' unless Shopify::FeatureGate.enabled?(account: account)
  end

  def redirect_callback_uri = "#{frontend_url}/shopify/callback"

  def shopify_integration_url = "#{frontend_url}/app/accounts/#{account.id}/settings/integrations/shopify"

  def shopify_billing_url = "#{frontend_url}/app/accounts/#{account.id}/settings/billing?shop=#{CGI.escape(params[:shop])}"

  def error_redirect_url
    if @account_id
      begin
        "#{shopify_integration_url}?error=true"
      rescue ActiveRecord::RecordNotFound
        "#{frontend_url}?error=true"
      end
    else
      "#{frontend_url}?error=true"
    end
  end

  def frontend_url = ENV.fetch('FRONTEND_URL', '')

  def oauth_state_key(state)
    "shopify_oauth_state:#{state}"
  end

  def valid_shop_domain?
    return false if params[:shop].blank?

    # Shopify shop domains must match: *.myshopify.com or *.myshopify.io (for dev shops)
    params[:shop].match?(/\A[a-zA-Z0-9][a-zA-Z0-9\-]*\.myshopify\.(com|io)\z/)
  end

  def valid_hmac?
    hmac = params[:hmac].to_s
    return false unless hmac.match?(/\A[0-9a-f]{64}\z/)

    # Shopify HMAC validation
    # Reference: https://shopify.dev/docs/apps/build/authentication-authorization/get-access-tokens
    query_params = request.query_parameters.except('hmac')
    query_string = URI.encode_www_form(query_params.sort)

    # Compute HMAC-SHA256
    computed_hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('SHA256'), client_secret, query_string)

    ActiveSupport::SecurityUtils.secure_compare(computed_hmac, hmac)
  end
end