require 'fluxx/resource' module Fluxx # API Token handler class Token < Resource GRANT_TYPE = 'client_credentials' EXPIRATION_DELTA = 60 path '/oauth/token' # Resource creation helper # # @param params [Hash] request parameters to pass to the endpoint # @return [Object] instance def self.create(params = {}) client_id = Thread.current.thread_variable_get(:FLUXX_CLIENT_ID) secret = Thread.current.thread_variable_get(:FLUXX_SECRET) super(params.merge( grant_type: GRANT_TYPE, client_id: client_id || ENV['FLUXX_CLIENT_ID'], client_secret: secret || ENV['FLUXX_SECRET'] )) end # Creates or refreshes a token # # @return [Fluxx::Token] instance def self.fresh @token ||= create @expires_in ||= 0 if Time.now.to_i > @expires_in + @token.expires_in - EXPIRATION_DELTA @token = create @expires_in = Time.now.to_i end @token end end end