Sha256: ee367148bdb13d45adf3a9497bfc350a8d9d5d987f68d4ed67446140e9081077

Contents?: true

Size: 1.38 KB

Versions: 16

Compression:

Stored size: 1.38 KB

Contents

module Lifen
  class Token

    @@refresh_lock = Mutex.new

    include Virtus.model(finalize: false)

    attribute :user, "Lifen::User"

    attribute :value, String
    attribute :expires_at, Integer

    attribute :load_from_db, Proc
    attribute :save_to_db, Proc

    def to_s
      value
    end

    def active?
      valid? and !needs_to_be_refreshed?
    end

    def valid?
      !value.nil? and value.length > 0 and !expires_at.nil?
    end

    def needs_to_be_refreshed?
      return true if has_expired?

      return (expires_at - expiration_margin) < Time.now.to_i
    end

    def has_expired?
      return true if expires_at.nil?

      return expires_at < Time.now.to_i
    end

    def refresh
      json = client.post("/oauth/admin/third_party/access_token?accountUuid=#{user.uuid}")

      self.value = json["access_token"]
      self.expires_at = Time.now.to_i + json["expires_in"].to_i
    end

    def refresh_once_if_needed
      @@refresh_lock.synchronize do

        load_from_db.call(self) if load_from_db.is_a? Proc

        return if active?
        refresh

        save_to_db.call(self) if save_to_db.is_a? Proc

        raise Error, "Token can't be refreshed" if !active?
      end
    end

    private

      def client
        @client ||= AppAuthenticatedClient.new
      end

      def expiration_margin
        Lifen.configuration.expiration_margin
      end

  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
lifen-3.0.0 lib/lifen/token.rb
lifen-2.4.0 lib/lifen/token.rb
lifen-2.3.0 lib/lifen/token.rb
lifen-2.2.0 lib/lifen/token.rb
lifen-2.1.0 lib/lifen/token.rb
lifen-2.0.0 lib/lifen/token.rb
lifen-1.6.8 lib/lifen/token.rb
lifen-1.6.7 lib/lifen/token.rb
lifen-1.6.6 lib/lifen/token.rb
lifen-1.6.5 lib/lifen/token.rb
lifen-1.6.4 lib/lifen/token.rb
lifen-1.6.3 lib/lifen/token.rb
lifen-1.6.2 lib/lifen/token.rb
lifen-1.6.1 lib/lifen/token.rb
lifen-1.6.0 lib/lifen/token.rb
lifen-1.5.2 lib/lifen/token.rb