Sha256: 1451d915d93bef4fb0836f503b964ec4b6beaca3b7cad10df45a9c5a179248ea

Contents?: true

Size: 1.99 KB

Versions: 3

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

require 'active_support/core_ext/numeric/time'

module Wso2Toolbox
  module TokenManager
    module Adapters
      module RailsCachedAdapter
        class << self
          TOKEN_DELAY = 5.minutes

          def generate_token
            new_token if expired_token?
            refresh_token unless active_token?
            store_token(Setting.token_for_job)
          end

          private

          def new_token
            token_params =
              Wso2Toolbox::TokenManager::ApiManagerService.create_token
            build_settings(token_params)
          end

          def refresh_token
            token_params =
              Wso2Toolbox::TokenManager::ApiManagerService.refresh_token(
                Setting.refresh_token
              )
            Wso2Toolbox::TokenManager::ApiManagerService.revoke_token(
              Setting.access_token
            )
            build_settings(token_params)
          end

          def store_token(token)
            RequestStore.store[:token] = token
          end

          def build_settings(token_params)
            Setting.access_token = token_params[:access_token]
            Setting.refresh_token = token_params[:refresh_token]
            build_token_for_job(token_params[:token_type],
                                token_params[:access_token])
            build_token_time_for_job(token_params[:expires_in])
          end

          def build_token_for_job(token_type, access_token)
            Setting.token_for_job = "#{token_type} #{access_token}"
          end

          def build_token_time_for_job(expires_in)
            Setting.token_time_for_job = expires_in.to_i.seconds.from_now
          end

          def expired_token?
            return true unless Setting.token_time_for_job

            Time.now > Time.parse(Setting.token_time_for_job)
          end

          def active_token?
            Time.parse(Setting.token_time_for_job.to_s) - TOKEN_DELAY > Time.now
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
wso2_toolbox-0.3.3 lib/wso2_toolbox/token_manager/adapters/rails_cached_adapter.rb
wso2_toolbox-0.3.2 lib/wso2_toolbox/token_manager/adapters/rails_cached_adapter.rb
wso2_toolbox-0.3.1 lib/wso2_toolbox/token_manager/adapters/rails_cached_adapter.rb