class OpenAPI::AuthToken

Attributes

key[RW]
expires[RW]
expires_at[RW]
expires_in[RW]
header[RW]
header_format[RW]
key[RW]
options[RW]
refresh_token[RW]
token[RW]

Public Class Methods

fetch(key) click to toggle source
# File lib/openapi/auth_token.rb, line 17
def fetch(key)
  if OpenAPI.cache
    begin
      puts "fetch new: #{OpenAPI.cache.get(key)}"
      return self.new(JSON.parse(OpenAPI.cache.get(key)))
    rescue => e
      puts e.message
    end
  end
end
fetch_or_create(key, opts) click to toggle source
# File lib/openapi/auth_token.rb, line 8
def fetch_or_create(key, opts)
  auth_token = fetch(key)
  if auth_token.nil? || auth_token.renew?
    self.class.new(opts)
  else
    auth_token
  end
end
new(opts={}, save=false) click to toggle source
# File lib/openapi/auth_token.rb, line 58
def initialize(opts={}, save=false)
  @options = {}
  opts = {"token" => nil,
    "refresh_token" => nil,
    "expires_at" => nil,
    "expires_in" => nil,
    "key" => nil,
    "header" => "Authorization",
    "header_format" => "Bearer %s"}.merge(opts)
  update(opts, save)
end

Public Instance Methods

[](key) click to toggle source
# File lib/openapi/auth_token.rb, line 54
def [](key)
  @options[key.to_s]
end
headers() click to toggle source
# File lib/openapi/auth_token.rb, line 70
def headers
  {header => header_format % token}
end
new_auth_token() click to toggle source
# File lib/openapi/auth_token.rb, line 99
def new_auth_token()
  raise NotImplementedError
end
renew?() click to toggle source
# File lib/openapi/auth_token.rb, line 95
def renew?
  @token == nil || @expires_at.to_i < Time.now.utc.to_i
end
renew_token() click to toggle source
# File lib/openapi/auth_token.rb, line 104
def renew_token
  new_token = self.class.fetch(self.key)
  if new_token.nil? || new_token.renew?
    self.new_auth_token
    self.save
  else
    update(new_token.to_hash)
  end
end
save() click to toggle source
# File lib/openapi/auth_token.rb, line 78
def save
  if OpenAPI.cache
    OpenAPI.cache.set(key, to_hash.to_json, expires_in + 2.hours)
  end
end
to_hash() click to toggle source
# File lib/openapi/auth_token.rb, line 84
def to_hash
  @options
end
update(opts={}, save=false) click to toggle source
# File lib/openapi/auth_token.rb, line 37
def update(opts={}, save=false)
  @options = @options.merge(opts)
  @options.each do |k, v|
    instance_variable_set("@#{k}", v)
  end
  @token ||= @options.delete("access_token")
  @options["token"] = @token
  if opts.has_key?("expires_at") && !opts["expires_at"].nil?
    @expires_at = opts["expires_at"].to_i
  elsif opts.has_key?("expires_in") && !opts["expires_in"].nil?
    @options.delete("expires_in")
    @expires_at = Time.now.utc.to_i + opts["expires_in"]
    @options["expires_at"] = @expires_at
  end
  self.save if save
end