Sha256: 27fea02ad2f97ea8692d9259aae90143bead4a199869fa519f7a2343c1dc6188

Contents?: true

Size: 1.34 KB

Versions: 247

Compression:

Stored size: 1.34 KB

Contents

require 'openssl'

module OmniAuth
  module Facebook
    class SignedRequest
      class UnknownSignatureAlgorithmError < NotImplementedError; end
      SUPPORTED_ALGORITHM = 'HMAC-SHA256'

      attr_reader :value, :secret

      def self.parse(value, secret)
        new(value, secret).payload
      end

      def initialize(value, secret)
        @value = value
        @secret = secret
      end

      def payload
        @payload ||= parse_signed_request
      end

      private

      def parse_signed_request
        signature, encoded_payload = value.split('.')
        return if signature.nil?

        decoded_hex_signature = base64_decode_url(signature)
        decoded_payload = MultiJson.decode(base64_decode_url(encoded_payload))

        unless decoded_payload['algorithm'] == SUPPORTED_ALGORITHM
          raise UnknownSignatureAlgorithmError, "unknown algorithm: #{decoded_payload['algorithm']}"
        end

        if valid_signature?(decoded_hex_signature, encoded_payload)
          decoded_payload
        end
      end

      def valid_signature?(signature, payload, algorithm = OpenSSL::Digest::SHA256.new)
        OpenSSL::HMAC.digest(algorithm, secret, payload) == signature
      end

      def base64_decode_url(value)
        value += '=' * (4 - value.size.modulo(4))
        Base64.decode64(value.tr('-_', '+/'))
      end
    end
  end
end

Version data entries

247 entries across 247 versions & 3 rubygems

Version Path
j1-template-2024.3.17 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.3.16 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.3.15 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.3.14 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.3.13 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.3.12 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.2.1 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.2.0 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.1.5 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.1.4 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.1.3 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.1.2 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.1.1 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.1.0 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.0.3 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.0.2 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.0.1 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2024.0.0 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2023.10.2 lib/j1_app/omniauth/facebook/signed_request.rb
j1-template-2023.10.1 lib/j1_app/omniauth/facebook/signed_request.rb