Sha256: ad7804236ef8e4d44c9094363c126cf290b54c52e92ea22388bcfdc09abe0f1e

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 KB

Contents

require 'mechanize'

module MechanizedAuthorization
  class << self
    def client
      @client ||= begin
        agent = Mechanize.new
        
        configure
        agent.get VkontakteApi.authorization_url(scope: [:friends, :groups], type: :client)
        
        agent.page.form_with(action: /login.vk.com/) do |form|
          form.email = settings.email
          form.pass  = settings.password
        end.submit
        
        # extra form in some cases
        agent.page.form.submit if agent.page.uri.fragment.nil?
        
        # uri.fragment: access_token=ee6b952fa432c70&expires_in=86400&user_id=123456
        token = agent.page.uri.fragment.split('&').each_with_object(Hash.new) do |pair, hash|
          key, value = pair.split('=')
          hash[key] = value
        end.fetch('access_token')
        
        VkontakteApi::Client.new(token)
      end
    end
    
    def on?
      !off?
    end
    
  private
    def off?
      ENV['NO_AUTH'] || !File.exists?(credentials_path)
    end
    
    def configure
      VkontakteApi.configure do |config|
        config.app_id     = settings.app_id
        config.app_secret = settings.app_secret
      end
    end
    
    def settings
      @settings ||= Hashie::Mash.new(settings_hash)
    end
    
    def settings_hash
      YAML.load_file(credentials_path)
    end
    
    def credentials_path
      File.expand_path('../credentials.yml', __FILE__)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
vkontakte_api-1.4.3 spec/support/mechanized_authorization.rb
vkontakte_api-1.4.2 spec/support/mechanized_authorization.rb
vkontakte_api-1.4 spec/support/mechanized_authorization.rb