Sha256: 26c2f425742f5580f6e8b188b4ff1bdd7d6a05554f38854a1acf2bc4fece5638

Contents?: true

Size: 1.78 KB

Versions: 12

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module ShopifyApp
  class JWT
    WARN_EXCEPTIONS = [
      ::JWT::DecodeError,
      ::JWT::ExpiredSignature,
      ::JWT::ImmatureSignature,
      ::JWT::VerificationError,
      ::ShopifyApp::InvalidAudienceError,
      ::ShopifyApp::InvalidDestinationError,
      ::ShopifyApp::MismatchedHostsError,
    ]

    def initialize(token)
      @token = token
      set_payload
    end

    def shopify_domain
      @payload && ShopifyApp::Utils.sanitize_shop_domain(@payload["dest"])
    end

    def shopify_user_id
      @payload["sub"].to_i if @payload && @payload["sub"]
    end

    def expire_at
      @payload["exp"].to_i if @payload && @payload["exp"]
    end

    private

    def set_payload
      payload, _ = parse_token_data(ShopifyApp.configuration&.secret, ShopifyApp.configuration&.old_secret)
      @payload = validate_payload(payload)
    rescue *WARN_EXCEPTIONS
      nil
    end

    def parse_token_data(secret, old_secret)
      ::JWT.decode(@token, secret, true, { algorithm: "HS256" })
    rescue ::JWT::VerificationError
      raise unless old_secret

      ::JWT.decode(@token, old_secret, true, { algorithm: "HS256" })
    end

    def validate_payload(payload)
      dest_host = ShopifyApp::Utils.sanitize_shop_domain(payload["dest"])
      iss_host = ShopifyApp::Utils.sanitize_shop_domain(payload["iss"])
      api_key = ShopifyApp.configuration.api_key

      raise ::ShopifyApp::InvalidAudienceError,
        "'aud' claim does not match api_key" unless payload["aud"] == api_key
      raise ::ShopifyApp::InvalidDestinationError, "'dest' claim host not a valid shopify host" unless dest_host

      raise ::ShopifyApp::MismatchedHostsError,
        "'dest' claim host does not match 'iss' claim host" unless dest_host == iss_host

      payload
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
shopify_app-22.1.0 lib/shopify_app/session/jwt.rb
shopify_app-22.0.1 lib/shopify_app/session/jwt.rb
shopify_app-22.00.0 lib/shopify_app/session/jwt.rb
shopify_app-21.10.0 lib/shopify_app/session/jwt.rb
shopify_app-21.9.0 lib/shopify_app/session/jwt.rb
shopify_app-21.8.1 lib/shopify_app/session/jwt.rb
shopify_app-21.8.0 lib/shopify_app/session/jwt.rb
shopify_app-21.7.0 lib/shopify_app/session/jwt.rb
shopify_app-21.6.0 lib/shopify_app/session/jwt.rb
shopify_app-21.5.0 lib/shopify_app/session/jwt.rb
shopify_app-21.4.1 lib/shopify_app/session/jwt.rb
shopify_app-21.4.0 lib/shopify_app/session/jwt.rb