Sha256: e47aead9a22f330cebdc0269b606225858ce8e0c136ae7293be56b79cc6073da

Contents?: true

Size: 1.62 KB

Versions: 47

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true
require 'base64'
require 'openssl'

module Alula
  # Helper class to build JWT tokens
  # Used for internal video API calls or video API calls with a customer ID
  module JwtHelper
    ONE_HOUR = 60 * 60
    class << self
      def build_jwt_token(jwt_payload)
        jwt_secret = Alula::Client.config.video_api_key

        header = build_jwt_header

        token_data = add_timestamp_to_payload(jwt_payload)

        encoded_header = convert_to_base64(JSON.generate(header))
        encoded_data = convert_to_base64(JSON.generate(token_data))

        token = "#{encoded_header}.#{encoded_data}"
        signature = sign_token(token, jwt_secret)

        "#{token}.#{signature}"
      end

      def build_jwt_header
        {
          'typ' => 'JWT',
          'alg' => 'HS256'
        }
      end

      def add_timestamp_to_payload(payload)
        current_timestamp = Time.now.to_i
        payload.merge(
          {
            'iat' => current_timestamp,
            'exp' => current_timestamp + ONE_HOUR # expiry time is 60 minutes from time of creation
          }
        )
      end

      def sign_token(token, secret)
        signature = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), secret, token)
        convert_to_base64(signature)
      end

      def convert_to_base64(source)
        # Encode in classical base64,
        encoded_source = Base64.strict_encode64(source)

        # Remove padding equal characters,
        encoded_source = encoded_source.gsub('=', '')

        # Replace characters according to base64url specifications,
        encoded_source.tr('+/', '-_')
      end
    end
  end
end

Version data entries

47 entries across 47 versions & 1 rubygems

Version Path
alula-ruby-2.12.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.11.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.10.1 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.10.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.9.1 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.9.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.8.1 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.8.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.7.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.6.3 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.6.2 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.6.1 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.6.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.5.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.4.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.3.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.2.0 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.1.2 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.1.1 lib/alula/helpers/jwt_helper.rb
alula-ruby-2.1.0 lib/alula/helpers/jwt_helper.rb