Sha256: 788ed8853480fb557523896c874df8604376c506d77b395c83af92a51e72bbe5

Contents?: true

Size: 1.1 KB

Versions: 2

Compression:

Stored size: 1.1 KB

Contents

require 'active_support/core_ext/string/conversions'

module Formi9
  module OAuth
    def access_token
      token = Rails.cache.read(access_token_cache_key)

      if token.present?
        return token
      else
        reset_token
        Rails.cache.read(access_token_cache_key)
      end
    end

    def reset_token
      connection = Faraday.new endpoint, :ssl => {:verify => ssl_verify }
      response = connection.post('login', {id: partner_id, username: username, password: password} )
      raise CredentialAreInvalid.new('Credentials are missing or invalid.') if response.status != 200
      body = JSON.parse(response.body)
      if Rails.cache.read(access_token_cache_key).nil?
        Rails.cache.write(access_token_cache_key, body['accessToken'], expires_in: token_cache_duration(body['expirationDateUtc']))
      end
    end

    def access_token_cache_key
      Digest::MD5.hexdigest([partner_id, username, password].join)
    end

    def token_cache_duration(timestamp)
      max = 6.days.to_i
      duration = timestamp.to_datetime.utc - Time.now
      duration > max ? max : duration
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
formi9-0.1.8 lib/formi9/oauth.rb
formi9-0.1.7 lib/formi9/oauth.rb