Sha256: 704814dfaa1db1fe1fa35e7e9407f8e5462ecac1d1dc131a5b04e141a2c81265

Contents?: true

Size: 1.55 KB

Versions: 4

Compression:

Stored size: 1.55 KB

Contents

require 'active_support/concern'
require 'active_record'

module Devise
  module Oauth2Providable
    module ExpirableToken
      extend ActiveSupport::Concern

      module ClassMethods
        def expires_according_to(config_name)
          cattr_accessor :default_lifetime
          self.default_lifetime = Rails.application.config.devise_oauth2_providable[config_name]

          belongs_to :user
          belongs_to :client

          after_initialize :init_token, :on => :create, :unless => :token?
          after_initialize :init_expires_at, :on => :create, :unless => :expires_at?
          validates :expires_at, :presence => true
          validates :client, :presence => true
          validates :token, :presence => true, :uniqueness => true

          scope :not_expired, lambda {
            where(self.arel_table[:expires_at].gteq(Time.now.utc))
          }
          default_scope not_expired

          include LocalInstanceMethods
        end
      end

      module LocalInstanceMethods
        # number of seconds until the token expires
        def expires_in
          (expires_at - Time.now.utc).to_i
        end

        # forcefully expire the token
        def expired!
          self.expires_at = Time.now.utc
          self.save!
        end

        private

        def init_token
          self.token = Devise::Oauth2Providable.random_id
        end
        def init_expires_at
          self.expires_at = self.default_lifetime.from_now
        end
      end
    end
  end
end

ActiveRecord::Base.send :include, Devise::Oauth2Providable::ExpirableToken

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
devise_oauth2_providable-1.0.5 lib/devise/oauth2_providable/expirable_token.rb
devise_oauth2_providable-1.0.4 lib/devise/oauth2_providable/expirable_token.rb
devise_oauth2_providable-1.0.3 lib/devise/oauth2_providable/expirable_token.rb
devise_oauth2_providable-1.0.2 lib/devise/oauth2_providable/expirable_token.rb