Sha256: d93258f008c88ca16e74320601b437364f41c78e556b02feabcbd6f0808cec6e

Contents?: true

Size: 1.74 KB

Versions: 8

Compression:

Stored size: 1.74 KB

Contents

module MangoPay
  module AuthorizationToken

    class Manager

      class << self
        def storage
          @@storage ||= StaticStorage.new
        end
        def storage= (storage)
          @@storage = storage
        end
      end

      def self.get_token
        token = storage.get
        if token.nil? || token['timestamp'].nil? || token['timestamp'] <= Time.now
          token = MangoPay.request(:post, '/api/oauth/token', {}, {}, {}, Proc.new do |req|
            cfg = MangoPay.configuration
            req.basic_auth cfg.client_id, cfg.client_passphrase
            req.body = 'grant_type=client_credentials'
          end)
          token['timestamp'] = Time.now + token['expires_in'].to_i
          storage.store token
        end
        token
      end
    end

    class StaticStorage
      def get
        @@token ||= nil
      end
      def store(token)
        @@token = token
      end
    end

    class FileStorage
      require 'yaml'
      @temp_dir

      def initialize(temp_dir = nil)
        @temp_dir = temp_dir || MangoPay.configuration.temp_dir
        if !@temp_dir
          raise "Path to temporary folder is not defined"
        end
      end

      def get
        begin
          f = File.open(file_path, File::RDONLY)
          f.flock(File::LOCK_SH)
          txt = f.read
          f.close
          YAML.load(txt) || nil
        rescue Errno::ENOENT
          nil
        end
      end

      def store(token)
        File.open(file_path, File::RDWR|File::CREAT, 0644) do |f|
          f.flock(File::LOCK_EX)
          f.truncate(0)
          f.rewind
          f.puts(YAML.dump(token))
        end
      end

      def file_path
        File.join(@temp_dir, "MangoPay.AuthorizationToken.FileStore.tmp")
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
mangopay-3.0.9 lib/mangopay/authorization_token.rb
mangopay-3.0.8 lib/mangopay/authorization_token.rb
mangopay-3.0.7 lib/mangopay/authorization_token.rb
mangopay-3.0.6 lib/mangopay/authorization_token.rb
mangopay-3.0.5 lib/mangopay/authorization_token.rb
mangopay-3.0.4 lib/mangopay/authorization_token.rb
mangopay-3.0.3 lib/mangopay/authorization_token.rb
mangopay-3.0.2 lib/mangopay/authorization_token.rb