Class: Authoritarian::Twitter

Inherits:
Object
  • Object
show all
Defined in:
lib/authoritarian/twitter.rb

Overview

This class performs OAuth authorization for Twitter user accounts.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(consumer_key = nil, consumer_secret = nil) ⇒ Twitter

Creates a Twitter OAuth authorizer.



9
10
11
12
# File 'lib/authoritarian/twitter.rb', line 9

def initialize(consumer_key=nil, consumer_secret=nil)
  self.consumer_key    = consumer_key
  self.consumer_secret = consumer_secret
end

Instance Attribute Details

#consumer_keyObject

The consumer key for the application that is authorizing the user.



20
21
22
# File 'lib/authoritarian/twitter.rb', line 20

def consumer_key
  @consumer_key
end

#consumer_secretObject

The consumer secret for the application that is authorizing the user.



23
24
25
# File 'lib/authoritarian/twitter.rb', line 23

def consumer_secret
  @consumer_secret
end

Instance Method Details

#authorize(username, password) ⇒ Object

Public Methods



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/authoritarian/twitter.rb', line 30

def authorize(username, password)
  # Generate request token
  request_token = consumer.get_request_token
  
  # Create in-process browser
  mechanize = Mechanize.new do |agent|
    #agent.user_agent_alias = 'Authoritarian'
  end

  # Request authorization
  mechanize.get(generate_authorize_url(request_token)) do ||
    # Login and allow
    form = *.forms
    form.field_with(:name => 'session[username_or_email]').value = username
    form.field_with(:name => 'session[password]').value = password
    auth_page = form.submit(form.button_with(:value => 'Allow'))
    
    # Verify returned page has no errors
    error = auth_page.parser.css('p.oauth-errors').text.strip
    if error != ''
      raise Authoritarian::InvalidLoginError.new(error)
    end
    
    # If not then get access token from PIN
    pin = auth_page.parser.css('div#oauth_pin').text.strip

    # Create OAuth token from PIN
    access_token = request_token.get_access_token(:oauth_verifier => pin)
    return {:token => access_token.token, :secret => access_token.secret}
  end

  return nil
end