Sha256: d42d29e7b293104f57709d3bec669f2a095f4abd58fb3fafda479f17843cbd4b

Contents?: true

Size: 1.22 KB

Versions: 1

Compression:

Stored size: 1.22 KB

Contents

module Lifen
  class Token

    @@lock = Mutex.new

    include Virtus.model(finalize: false)

    attribute :user, "Lifen::User"

    attribute :value, String
    attribute :expires_at, Integer

    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
      @@lock.synchronize do

        yield(self) if block_given?

        return if active?

        refresh

        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

1 entries across 1 versions & 1 rubygems

Version Path
lifen-1.5.0 lib/lifen/token.rb