class Twurl::OAuthClient

Constants

METHODS
OAUTH_CLIENT_OPTIONS

Attributes

username[R]

Public Class Methods

has_oauth_options?(options) click to toggle source
   # File lib/twurl/oauth_client.rb
29 def has_oauth_options?(options)
30   (options.consumer_key && options.consumer_secret && options.access_token && options.token_secret) ? true : false
31 end
load_client_for_app_only_auth(options, consumer_key) click to toggle source
   # File lib/twurl/oauth_client.rb
66 def load_client_for_app_only_auth(options, consumer_key)
67   if options.command == 'authorize'
68     AppOnlyOAuthClient.new(options)
69   else
70     AppOnlyOAuthClient.new(
71       options.oauth_client_options.merge(
72         'bearer_token' => rcfile.bearer_tokens.to_hash[consumer_key]
73       )
74     )
75   end
76 end
load_client_for_non_profile_app_only_auth(options) click to toggle source
   # File lib/twurl/oauth_client.rb
78 def load_client_for_non_profile_app_only_auth(options)
79   AppOnlyOAuthClient.new(
80     options.oauth_client_options.merge(
81       'bearer_token' => rcfile.bearer_tokens.to_hash[options.consumer_key]
82     )
83   )
84 end
load_client_for_username(username) click to toggle source
   # File lib/twurl/oauth_client.rb
42 def load_client_for_username(username)
43   if user_profiles = rcfile[username]
44     if user_profiles.values.size == 1
45       new(user_profiles.values.first)
46     else
47       raise Exception, "There is more than one consumer key associated with #{username}. Please specify which consumer key you want as well."
48     end
49   else
50     raise Exception, "No profile for #{username}"
51   end
52 end
load_client_for_username_and_consumer_key(username, consumer_key) click to toggle source
   # File lib/twurl/oauth_client.rb
33 def load_client_for_username_and_consumer_key(username, consumer_key)
34   user_profiles = rcfile[username]
35   if user_profiles && attributes = user_profiles[consumer_key]
36     new(attributes)
37   else
38     raise Exception, "No profile for #{username}"
39   end
40 end
load_default_client(options) click to toggle source
    # File lib/twurl/oauth_client.rb
 86 def load_default_client(options)
 87   return if options.command == 'bearer_tokens'
 88 
 89   exception_message = "You must authorize first."
 90   app_only_exception_message = "To use --bearer option, you need to authorize (OAuth1.0a) and create at least one user profile (~/.twurlrc):\n\n" \
 91                                "twurl authorize -c key -s secret\n" \
 92                                "\nor, you can specify issued token's consumer_key directly:\n" \
 93                                "(to see your issued tokens: 'twurl bearer_tokens')\n\n" \
 94                                "twurl --bearer -c key '/path/to/api'"
 95 
 96   raise Exception, "#{options.app_only ? app_only_exception_message : exception_message}" unless rcfile.default_profile
 97   if options.app_only
 98       raise Exception, "No available bearer token found for consumer_key:#{rcfile.default_profile_consumer_key}" \
 99         unless rcfile.has_bearer_token_for_consumer_key?(rcfile.default_profile_consumer_key)
100       load_client_for_app_only_auth(options, rcfile.default_profile_consumer_key)
101   else
102     load_client_for_username_and_consumer_key(*rcfile.default_profile)
103   end
104 end
load_from_options(options) click to toggle source
   # File lib/twurl/oauth_client.rb
11 def load_from_options(options)
12   if options.command == 'request' && has_oauth_options?(options)
13     load_new_client_from_oauth_options(options)
14   elsif options.command == 'request' && options.app_only && options.consumer_key
15     load_client_for_non_profile_app_only_auth(options)
16   elsif rcfile.has_oauth_profile_for_username_with_consumer_key?(options.username, options.consumer_key)
17     load_client_for_username_and_consumer_key(options.username, options.consumer_key)
18   elsif options.username
19     load_client_for_username(options.username)
20   elsif options.command == 'authorize' && options.app_only
21     load_client_for_app_only_auth(options, options.consumer_key)
22   elsif options.command == 'authorize'
23     load_new_client_from_options(options)
24   else
25     load_default_client(options)
26   end
27 end
load_new_client_from_oauth_options(options) click to toggle source
   # File lib/twurl/oauth_client.rb
58 def load_new_client_from_oauth_options(options)
59   new(options.oauth_client_options.merge(
60       'token' => options.access_token,
61       'secret' => options.token_secret
62     )
63   )
64 end
load_new_client_from_options(options) click to toggle source
   # File lib/twurl/oauth_client.rb
54 def load_new_client_from_options(options)
55   new(options.oauth_client_options)
56 end
new(options = {}) click to toggle source
    # File lib/twurl/oauth_client.rb
110 def initialize(options = {})
111   @username        = options['username']
112   @consumer_key    = options['consumer_key']
113   @consumer_secret = options['consumer_secret']
114   @token           = options['token']
115   @secret          = options['secret']
116   configure_http!
117 end
rcfile(reload = false) click to toggle source
  # File lib/twurl/oauth_client.rb
4 def rcfile(reload = false)
5   if reload || @rcfile.nil?
6     @rcfile = RCFile.new
7   end
8   @rcfile
9 end

Public Instance Methods

access_token() click to toggle source
    # File lib/twurl/oauth_client.rb
281 def access_token
282   @access_token ||= OAuth::AccessToken.new(consumer, token, secret)
283 end
authorized?() click to toggle source
    # File lib/twurl/oauth_client.rb
228 def authorized?
229   oauth_response = fetch_verify_credentials
230   oauth_response.class == Net::HTTPOK
231 end
build_request_from_options(options, &block) click to toggle source
    # File lib/twurl/oauth_client.rb
129 def build_request_from_options(options, &block)
130   request_class = METHODS.fetch(options.request_method.to_sym)
131   request = request_class.new(options.path, options.headers)
132 
133   if options.upload && options.upload['file'].count > 0
134     boundary = "00Twurl" + rand(1000000000000000000).to_s + "lruwT99"
135     multipart_body = []
136     file_field = options.upload['filefield'] ? options.upload['filefield'] : 'media[]'
137 
138     options.data.each {|key, value|
139       multipart_body << "--#{boundary}\r\n"
140       multipart_body << "Content-Disposition: form-data; name=\"#{key}\"\r\n"
141       multipart_body << "\r\n"
142       multipart_body << value
143       multipart_body << "\r\n"
144     }
145 
146     options.upload['file'].each {|filename|
147       multipart_body << "--#{boundary}\r\n"
148       multipart_body << "Content-Disposition: form-data; name=\"#{file_field}\"; filename=\"#{File.basename(filename)}\"\r\n"
149       multipart_body << "Content-Type: application/octet-stream\r\n"
150       multipart_body << "Content-Transfer-Encoding: base64\r\n" if options.upload['base64']
151       multipart_body << "\r\n"
152 
153       if options.upload['base64']
154         enc = Base64.encode64(File.binread(filename))
155         multipart_body << enc
156       else
157         multipart_body << File.binread(filename)
158       end
159     }
160 
161     multipart_body << "\r\n--#{boundary}--\r\n"
162 
163     request.body = multipart_body.join
164     request.content_type = "multipart/form-data, boundary=\"#{boundary}\""
165   elsif request.content_type && options.data
166     request.body = options.data.keys.first
167   elsif options.data
168     request.content_type = "application/x-www-form-urlencoded"
169     if options.data.length == 1 && options.data.values.first == nil
170       request.body = options.data.keys.first
171     else
172       request.body = options.data.map do |key, value|
173         "#{key}=#{CGI.escape value}"
174       end.join("&")
175     end
176   end
177   request
178 end
configure_http!() click to toggle source
    # File lib/twurl/oauth_client.rb
259 def configure_http!
260   consumer.http.set_debug_output(Twurl.options.debug_output_io) if Twurl.options.trace
261   consumer.http.read_timeout = consumer.http.open_timeout = Twurl.options.timeout || 60
262   consumer.http.open_timeout = Twurl.options.connection_timeout if Twurl.options.connection_timeout
263   # Only override if Net::HTTP support max_retries (since Ruby >= 2.5)
264   consumer.http.max_retries = 0 if consumer.http.respond_to?(:max_retries=)
265   if Twurl.options.ssl?
266     consumer.http.use_ssl     = true
267     consumer.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
268   end
269 end
consumer() click to toggle source
    # File lib/twurl/oauth_client.rb
271 def consumer
272   @consumer ||=
273     OAuth::Consumer.new(
274       consumer_key,
275       consumer_secret,
276       :site => Twurl.options.base_url,
277       :proxy => Twurl.options.proxy
278     )
279 end
exchange_credentials_for_access_token() click to toggle source
    # File lib/twurl/oauth_client.rb
192 def exchange_credentials_for_access_token
193   response = begin
194     consumer.token_request(:post, consumer.access_token_path, nil, {})
195   rescue OAuth::Unauthorized
196     perform_pin_authorize_workflow
197   end
198   @token   = response[:oauth_token]
199   @secret  = response[:oauth_token_secret]
200 end
fetch_verify_credentials() click to toggle source
    # File lib/twurl/oauth_client.rb
224 def fetch_verify_credentials
225   access_token.get('/1.1/account/verify_credentials.json?include_entities=false&skip_status=true')
226 end
generate_authorize_url() click to toggle source
    # File lib/twurl/oauth_client.rb
210 def generate_authorize_url
211   request = consumer.create_signed_request(:get, consumer.authorize_path, @request_token, pin_auth_parameters)
212   params = request['Authorization'].sub(/^OAuth\s+/, '').split(/,\s+/).map { |p|
213     k, v = p.split('=')
214     v =~ /"(.*?)"/
215     "#{k}=#{CGI::escape($1)}"
216   }.join('&')
217   "#{Twurl.options.base_url}#{request.path}?#{params}"
218 end
needs_to_authorize?() click to toggle source
    # File lib/twurl/oauth_client.rb
233 def needs_to_authorize?
234   token.nil? || secret.nil?
235 end
perform_pin_authorize_workflow() click to toggle source
    # File lib/twurl/oauth_client.rb
202 def perform_pin_authorize_workflow
203   @request_token = consumer.get_request_token
204   CLI.puts("Go to #{generate_authorize_url} and paste in the supplied PIN")
205   pin = STDIN.gets
206   access_token = @request_token.get_access_token(:oauth_verifier => pin.chomp)
207   {:oauth_token => access_token.token, :oauth_token_secret => access_token.secret}
208 end
perform_request_from_options(options, &block) click to toggle source
    # File lib/twurl/oauth_client.rb
180 def perform_request_from_options(options, &block)
181   request = build_request_from_options(options)
182   request.oauth!(consumer.http, consumer, access_token)
183   request['user-agent'] = user_agent
184   consumer.http.request(request, &block)
185 end
pin_auth_parameters() click to toggle source
    # File lib/twurl/oauth_client.rb
220 def pin_auth_parameters
221   {'oauth_callback' => 'oob'}
222 end
save() click to toggle source
    # File lib/twurl/oauth_client.rb
237 def save
238   verify_has_username
239   self.class.rcfile << self
240 end
to_hash() click to toggle source
    # File lib/twurl/oauth_client.rb
250 def to_hash
251   OAUTH_CLIENT_OPTIONS.inject({}) do |hash, attribute|
252     if value = send(attribute)
253       hash[attribute] = value
254     end
255     hash
256   end
257 end
user_agent() click to toggle source
    # File lib/twurl/oauth_client.rb
187 def user_agent
188   "twurl version: #{Version} " \
189   "platform: #{RUBY_ENGINE} #{RUBY_VERSION} (#{RUBY_PLATFORM})"
190 end
verify_has_username() click to toggle source
    # File lib/twurl/oauth_client.rb
242 def verify_has_username
243   if username.nil? || username == ''
244     oauth_response = fetch_verify_credentials
245     oauth_response.body =~ /"screen_name"\s*:\s*"(.*?)"/
246     @username = $1
247   end
248 end