auth.rb 1.28 KB
class OauthClientPlugin::Auth < ApplicationRecord

  attr_accessible :profile, :external_person, :provider,
                  :enabled, :access_token, :expires_in, :type, :uid

  belongs_to :profile, class_name: 'Profile'
  belongs_to :external_person, class_name: 'ExternalPerson'
  belongs_to :provider, class_name: 'OauthClientPlugin::Provider'

  validates_presence_of :provider
  validates_uniqueness_of :profile_id, scope: :provider_id
  validates_uniqueness_of :external_person_id, scope: :provider_id

  validate :must_be_related_to_profile

  acts_as_having_settings field: :data

  def expires_in
    self.expires_at - Time.now
  end
  def expires_in= value
    self.expires_at = Time.now + value.to_i
  end

  def expired?
    Time.now > self.expires_at rescue true
  end
  def not_expired?
    not self.expired?
  end

  def self.create_for_strategy(strategy, args = {})
    namespace = self.name.split("::")[0]
    class_name = "#{namespace}::#{strategy.camelize}Auth"
    OauthClientPlugin::Auth.create!(args.merge(type: class_name))
  end

  def must_be_related_to_profile
    if self.profile.nil? && self.external_person.nil?
      self.errors.add(:base, "Must ")
    end
  end

  # Should be implemented by the Provider specific Auth classes
  def image_url(size = nil)
    nil
  end

end