Sha256: 81f3b79c49efb2e5c40df73822ad07a0594f7ba7b9101a63be95e610309a7088

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

module BookingSync::Engine::Model
  extend ActiveSupport::Concern

  included do
    validates :uid, uniqueness: true
  end

  module ClassMethods
    def from_omniauth(auth)
      find_or_initialize_by(uid: auth.uid, provider: auth.provider).tap do |account|
        account.name = auth.info.business_name
        account.update_token(auth.credentials)
        account.save!
      end
    end
  end

  def token
    @token ||= begin
      token_options = {}
      if oauth_refresh_token
        token_options[:refresh_token] = oauth_refresh_token
        token_options[:expires_at]    = oauth_expires_at
      end

      token = OAuth2::AccessToken.new(BookingSync::Engine.oauth_client,
        oauth_access_token, token_options)

      if token.expired?
        token = token.refresh!
        update_token!(token)
      end

      token
    end
  end

  def api
    @api ||= BookingSync::API::Client.new(token.token)
  end

  def update_token(token)
    self.oauth_access_token   = token.token
    self.oauth_refresh_token  = token.refresh_token
    self.oauth_expires_at     = token.expires_at
  end

  def update_token!(token)
    update_token(token)
    save!
  end

  def clear_token!
    self.oauth_access_token   = nil
    self.oauth_refresh_token  = nil
    self.oauth_expires_at     = nil
    save!
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bookingsync-engine-0.3.0 lib/bookingsync/engine/model.rb
bookingsync-engine-0.2.2 lib/bookingsync/engine/model.rb