@@ -2,7 +2,6 @@
require 'oauth/consumer'
require 'oauth/helper'
require 'oauth/token'
require 'oauth/version'
require 'oauth/signature/hmac/sha1'

module OAuth::Client
@@ -29,21 +28,25 @@ def timestamp

def oauth_parameters
{
'oauth_body_hash' => options[:body_hash],
'oauth_callback' => options[:oauth_callback],
'oauth_consumer_key' => options[:consumer].key,
'oauth_token' => options[:token] ? options[:token].token : '',
'oauth_signature_method' => options[:signature_method],
'oauth_timestamp' => timestamp,
'oauth_nonce' => nonce,
'oauth_verifier' => options[:oauth_verifier],
'oauth_version' => '1.0'
'oauth_version' => (options[:oauth_version] || '1.0'),
'oauth_session_handle' => options[:oauth_session_handle]
}.reject { |k,v| v.to_s == "" }
end

def signature(extra_options = {})
OAuth::Signature.sign(@request, { :uri => options[:request_uri],
:consumer => options[:consumer],
:token => options[:token] }.merge(extra_options) )
:token => options[:token],
:unsigned_parameters => options[:unsigned_parameters]
}.merge(extra_options) )
end

def signature_base_string(extra_options = {})
@@ -53,9 +56,14 @@ def signature_base_string(extra_options = {})
:parameters => oauth_parameters}.merge(extra_options) )
end

def hash_body
@options[:body_hash] = OAuth::Signature.body_hash(@request, :parameters => oauth_parameters)
end

def amend_user_agent_header(headers)
@oauth_ua_string ||= "OAuth gem v#{OAuth::VERSION}"
if headers['User-Agent']
# Net::HTTP in 1.9 appends Ruby
if headers['User-Agent'] && headers['User-Agent'] != 'Ruby'
headers['User-Agent'] += " (#{@oauth_ua_string})"
else
headers['User-Agent'] = @oauth_ua_string
@@ -66,7 +74,7 @@ def header
parameters = oauth_parameters
parameters.merge!('oauth_signature' => signature(options.merge(:parameters => parameters)))

header_params_str = parameters.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ')
header_params_str = parameters.sort.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ')

realm = "realm=\"#{options[:realm]}\", " if options[:realm]
"OAuth #{realm}#{header_params_str}"
@@ -2,7 +2,7 @@
require 'oauth/client/helper'
require 'oauth/request_proxy/net_http'

class Net::HTTPRequest
class Net::HTTPGenericRequest
include OAuth::Helper

attr_reader :oauth_helper
@@ -11,7 +11,7 @@ class Net::HTTPRequest
# this may add a header, additional query string parameters, or additional POST body parameters.
# The default scheme is +header+, in which the OAuth parameters as put into the +Authorization+
# header.
#
#
# * http - Configured Net::HTTP instance
# * consumer - OAuth::Consumer instance
# * token - OAuth::Token instance
@@ -20,53 +20,60 @@ class Net::HTTPRequest
#
# This method also modifies the <tt>User-Agent</tt> header to add the OAuth gem version.
#
# See Also: {OAuth core spec version 1.0, section 5.4.1}[http://oauth.net/core/1.0#rfc.section.5.4.1]
# See Also: {OAuth core spec version 1.0, section 5.4.1}[http://oauth.net/core/1.0#rfc.section.5.4.1],
# {OAuth Request Body Hash 1.0 Draft 4}[http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/4/spec.html]
def oauth!(http, consumer = nil, token = nil, options = {})
options = { :request_uri => oauth_full_request_uri(http),
:consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)

@oauth_helper = OAuth::Client::Helper.new(self, options)
helper_options = oauth_helper_options(http, consumer, token, options)
@oauth_helper = OAuth::Client::Helper.new(self, helper_options)
@oauth_helper.amend_user_agent_header(self)
self.send("set_oauth_#{options[:scheme]}")
@oauth_helper.hash_body if oauth_body_hash_required?
self.send("set_oauth_#{helper_options[:scheme]}")
end

# Create a string suitable for signing for an HTTP request. This process involves parameter
# normalization as specified in the OAuth specification. The exact normalization also depends
# on the <tt>options[:scheme]</tt> being used so this must match what will be used for the request
# itself. The default scheme is +header+, in which the OAuth parameters as put into the +Authorization+
# header.
#
#
# * http - Configured Net::HTTP instance
# * consumer - OAuth::Consumer instance
# * token - OAuth::Token instance
# * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+,
# +signature_method+, +nonce+, +timestamp+)
#
# See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1]
#
# See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1],
# {OAuth Request Body Hash 1.0 Draft 4}[http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/4/spec.html]
def signature_base_string(http, consumer = nil, token = nil, options = {})
options = { :request_uri => oauth_full_request_uri(http),
:consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)

OAuth::Client::Helper.new(self, options).signature_base_string
helper_options = oauth_helper_options(http, consumer, token, options)
oauth_helper = OAuth::Client::Helper.new(self, helper_options)
oauth_helper.hash_body if oauth_body_hash_required?
oauth_helper.signature_base_string
end

private

def oauth_full_request_uri(http)
def oauth_helper_options(http, consumer, token, options)
{ :request_uri => oauth_full_request_uri(http,options),
:consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)
end

def oauth_full_request_uri(http,options)
uri = URI.parse(self.path)
uri.host = http.address
uri.port = http.port

if options[:request_endpoint] && options[:site]
is_https = options[:site].match(%r(^https://))
uri.host = options[:site].gsub(%r(^https?://), '')
uri.port ||= is_https ? 443 : 80
end

if http.respond_to?(:use_ssl?) && http.use_ssl?
uri.scheme = "https"
else
@@ -76,22 +83,29 @@ def oauth_full_request_uri(http)
uri.to_s
end

def oauth_body_hash_required?
request_body_permitted? && !content_type.to_s.downcase.start_with?("application/x-www-form-urlencoded")
end

def set_oauth_header
self['Authorization'] = @oauth_helper.header
end

# FIXME: if you're using a POST body and query string parameters, using this
# method will convert those parameters on the query string into parameters in
# the body. this is broken, and should be fixed.
# FIXME: if you're using a POST body and query string parameters, this method
# will move query string parameters into the body unexpectedly. This may
# cause problems with non-x-www-form-urlencoded bodies submitted to URLs
# containing query string params. If duplicate parameters are present in both
# places, all instances should be included when calculating the signature
# base string.

def set_oauth_body
self.set_form_data(@oauth_helper.parameters_with_oauth)
self.set_form_data(@oauth_helper.stringify_keys(@oauth_helper.parameters_with_oauth))
params_with_sig = @oauth_helper.parameters.merge(:oauth_signature => @oauth_helper.signature)
self.set_form_data(params_with_sig)
self.set_form_data(@oauth_helper.stringify_keys(params_with_sig))
end

def set_oauth_query_string
oauth_params_str = @oauth_helper.oauth_parameters.map { |k,v| [escape(k), escape(v)] * "=" }.join("&")

uri = URI.parse(path)
if uri.query.to_s == ""
uri.query = oauth_params_str
@@ -3,6 +3,7 @@
require 'oauth/oauth'
require 'oauth/client/net_http'
require 'oauth/errors'
require 'cgi'

module OAuth
class Consumer
@@ -75,10 +76,10 @@ def initialize(consumer_key, consumer_secret, options = {})
@secret = consumer_secret

# ensure that keys are symbols
@options = @@default_options.merge(options.inject({}) { |options, (key, value)|
options[key.to_sym] = value
options
})
@options = @@default_options.merge(options.inject({}) do |opts, (key, value)|
opts[key.to_sym] = value
opts
end)
end

# The default http method
@@ -101,8 +102,8 @@ def uri(custom_uri = nil)
end
end

def get_access_token(request_token, request_options = {}, *arguments)
response = token_request(http_method, (access_token_url? ? access_token_url : access_token_path), request_token, request_options, *arguments)
def get_access_token(request_token, request_options = {}, *arguments, &block)
response = token_request(http_method, (access_token_url? ? access_token_url : access_token_path), request_token, request_options, *arguments, &block)
OAuth::AccessToken.from_hash(self, response)
end

@@ -120,12 +121,20 @@ def get_access_token(request_token, request_options = {}, *arguments)
# @request_token = @consumer.get_request_token({}, :foo => "bar")
#
# TODO oauth_callback should be a mandatory parameter
def get_request_token(request_options = {}, *arguments)
def get_request_token(request_options = {}, *arguments, &block)
# if oauth_callback wasn't provided, it is assumed that oauth_verifiers
# will be exchanged out of band
request_options[:oauth_callback] ||= OAuth::OUT_OF_BAND

response = token_request(http_method, (request_token_url? ? request_token_url : request_token_path), nil, request_options, *arguments)
request_options[:oauth_callback] ||= OAuth::OUT_OF_BAND unless request_options[:exclude_callback]

if block_given?
response = token_request(http_method,
(request_token_url? ? request_token_url : request_token_path),
nil,
request_options,
*arguments, &block)
else
response = token_request(http_method, (request_token_url? ? request_token_url : request_token_path), nil, request_options, *arguments)
end
OAuth::RequestToken.from_hash(self, response)
end

@@ -139,24 +148,22 @@ def get_request_token(request_options = {}, *arguments)
# @consumer.request(:get, '/people', @token, { :scheme => :query_string })
# @consumer.request(:post, '/people', @token, {}, @person.to_xml, { 'Content-Type' => 'application/xml' })
#
def request(http_method, path, token = nil, request_options = {}, *arguments, &block)
def request(http_method, path, token = nil, request_options = {}, *arguments)
if path !~ /^\//
@http = create_http(path)
_uri = URI.parse(path)
path = "#{_uri.path}#{_uri.query ? "?#{_uri.query}" : ""}"
end

# override the request with your own, this is useful for file uploads which Net::HTTP does not do
req = create_signed_request(http_method, path, token, request_options, *arguments)
rsp = if block_given?
http.request(req, &block)
else
http.request(req) end

return nil if block_given? and yield(req) == :done
rsp = http.request(req)
# check for an error reported by the Problem Reporting extension
# (http://wiki.oauth.net/ProblemReporting)
# note: a 200 may actually be an error; check for an oauth_problem key to be sure
if !(headers = rsp.to_hash["www-authenticate"]).nil? &&
(h = headers.select { |h| h =~ /^OAuth / }).any? &&
(h = headers.select { |hdr| hdr =~ /^OAuth / }).any? &&
h.first =~ /oauth_problem/

# puts "Header: #{h.first}"
@@ -185,21 +192,26 @@ def create_signed_request(http_method, path, token = nil, request_options = {},
# Creates a request and parses the result as url_encoded. This is used internally for the RequestToken and AccessToken requests.
def token_request(http_method, path, token = nil, request_options = {}, *arguments)
response = request(http_method, path, token, request_options, *arguments)

case response.code.to_i

when (200..299)
# symbolize keys
# TODO this could be considered unexpected behavior; symbols or not?
# TODO this also drops subsequent values from multi-valued keys
CGI.parse(response.body).inject({}) do |h,(k,v)|
h[k.to_sym] = v.first
h[k] = v.first
h
if block_given?
yield response.body
else
# symbolize keys
# TODO this could be considered unexpected behavior; symbols or not?
# TODO this also drops subsequent values from multi-valued keys
CGI.parse(response.body).inject({}) do |h,(k,v)|
h[k.strip.to_sym] = v.first
h[k.strip] = v.first
h
end
end
when (300..399)
# this is a redirect
response.error!
uri = URI.parse(response.header['location'])
response.error! if uri.path == path # careful of those infinite redirects
self.token_request(http_method, uri.path, token, request_options, arguments)
when (400..499)
raise OAuth::Unauthorized, response
else
@@ -221,6 +233,11 @@ def site
@options[:site].to_s
end

def request_endpoint
return nil if @options[:request_endpoint].nil?
@options[:request_endpoint].to_s
end

def scheme
@options[:scheme]
end
@@ -266,16 +283,24 @@ def proxy
@options[:proxy]
end

protected
protected

# Instantiates the http object
def create_http(_url = nil)


if !request_endpoint.nil?
_url = request_endpoint
end


if _url.nil? || _url[0] =~ /^\//
our_uri = URI.parse(site)
else
our_uri = URI.parse(_url)
end


if proxy.nil?
http_object = Net::HTTP.new(our_uri.host, our_uri.port)
else
@@ -292,7 +317,6 @@ def create_http(_url = nil)
else
http_object.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

http_object
end

@@ -302,18 +326,21 @@ def create_http_request(http_method, path, *arguments)

if [:post, :put].include?(http_method)
data = arguments.shift
data.reject! { |k,v| v.nil? } if data.is_a?(Hash)
end

# if the base site contains a path, add it now
uri = URI.parse(site)
path = uri.path + path if uri.path

headers = arguments.first.is_a?(Hash) ? arguments.shift : {}

case http_method
when :post
request = Net::HTTP::Post.new(path,headers)
request["Content-Length"] = 0 # Default to 0
request["Content-Length"] = '0' # Default to 0
when :put
request = Net::HTTP::Put.new(path,headers)
request["Content-Length"] = 0 # Default to 0
request["Content-Length"] = '0' # Default to 0
when :get
request = Net::HTTP::Get.new(path,headers)
when :delete
@@ -325,31 +352,35 @@ def create_http_request(http_method, path, *arguments)
end

if data.is_a?(Hash)
request.set_form_data(data)
form_data = {}
data.each {|k,v| form_data[k.to_s] = v if !v.nil?}
request.set_form_data(form_data)
elsif data
if data.respond_to?(:read)
request.body_stream = data
if data.respond_to?(:length)
request["Content-Length"] = data.length
request["Content-Length"] = data.length.to_s
elsif data.respond_to?(:stat) && data.stat.respond_to?(:size)
request["Content-Length"] = data.stat.size
request["Content-Length"] = data.stat.size.to_s
else
raise ArgumentError, "Don't know how to send a body_stream that doesn't respond to .length or .stat.size"
end
else
request.body = data.to_s
request["Content-Length"] = request.body.length
request["Content-Length"] = request.body.length.to_s
end
end

request
end

# Unset cached http instance because it cannot be marshalled when
# it has already been used and use_ssl is set to true
def marshal_dump(*args)
@http = nil
self
{:key => @key, :secret => @secret, :options => @options}
end

def marshal_load(data)
initialize(data[:key], data[:secret], data[:options])
end

end
end
@@ -0,0 +1,31 @@
# these are to backport methods from 1.8.7/1.9.1 to 1.8.6

class Object

unless method_defined?(:tap)
def tap
yield self
self
end
end

end

class String



unless method_defined?(:bytesize)
def bytesize
self.size
end
end

unless method_defined?(:bytes)
def bytes
require 'enumerator'
Enumerable::Enumerator.new(self, :each_byte)
end
end

end
@@ -11,4 +11,4 @@ def to_s
problem
end
end
end
end
@@ -9,4 +9,4 @@ def to_s
[request.code, request.message] * " "
end
end
end
end
@@ -5,19 +5,13 @@ module OAuth
module Helper
extend self

# Escape +value+ by URL encoding all non-reserved character.
# Escape +value+ by URL encoding all non-reserved character.
#
# See Also: {OAuth core spec version 1.0, section 5.1}[http://oauth.net/core/1.0#rfc.section.5.1]
# def escape(value)
# URI::escape(value.to_s, OAuth::RESERVED_CHARACTERS)
# end
def escape(value)
begin
URI::escape(value.to_s, OAuth::RESERVED_CHARACTERS)
rescue ArgumentError
URI::escape(value.to_s.force_encoding(Encoding::UTF_8),
OAuth::RESERVED_CHARACTERS)
end
URI::escape(value.to_s, OAuth::RESERVED_CHARACTERS)
rescue ArgumentError
URI::escape(value.to_s.force_encoding(Encoding::UTF_8), OAuth::RESERVED_CHARACTERS)
end

# Generate a random key of up to +size+ bytes. The value returned is Base64 encoded with non-word
@@ -41,17 +35,38 @@ def generate_timestamp #:nodoc:
# See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1]
def normalize(params)
params.sort.map do |k, values|

if values.is_a?(Array)
# make sure the array has an element so we don't lose the key
values << nil if values.empty?
# multiple values were provided for a single key
values.sort.collect do |v|
[escape(k),escape(v)] * "="
end
elsif values.is_a?(Hash)
normalize_nested_query(values, k)
else
[escape(k),escape(values)] * "="
end
end * "&"
end

#Returns a string representation of the Hash like in URL query string
# build_nested_query({:level_1 => {:level_2 => ['value_1','value_2']}}, 'prefix'))
# #=> ["prefix%5Blevel_1%5D%5Blevel_2%5D%5B%5D=value_1", "prefix%5Blevel_1%5D%5Blevel_2%5D%5B%5D=value_2"]
def normalize_nested_query(value, prefix = nil)
case value
when Array
value.map do |v|
normalize_nested_query(v, "#{prefix}[]")
end.flatten.sort
when Hash
value.map do |k, v|
normalize_nested_query(v, prefix ? "#{prefix}[#{k}]" : k)
end.flatten.sort
else
[escape(prefix), escape(value)] * "="
end
end

# Parse an Authorization / WWW-Authenticate header into a hash. Takes care of unescaping and
# removing surrounding quotes. Raises a OAuth::Problem if the header is not parsable into a
@@ -60,10 +75,10 @@ def normalize(params)
# hash = parse_header(headers['Authorization'] || headers['WWW-Authenticate'])
# hash['oauth_timestamp']
# #=>"1234567890"
#
#
def parse_header(header)
# decompose
params = header[6,header.length].split(/[,=]/)
params = header[6,header.length].split(/[,=&]/)

# odd number of arguments - must be a malformed header.
raise OAuth::Problem.new("Invalid authorization header") if params.size % 2 != 0
@@ -82,5 +97,13 @@ def parse_header(header)
def unescape(value)
URI.unescape(value.gsub('+', '%2B'))
end

def stringify_keys(hash)
new_h = {}
hash.each do |k, v|
new_h[k.to_s] = v.is_a?(Hash) ? stringify_keys(v) : v
end
new_h
end
end
end
@@ -4,7 +4,9 @@ module OAuth
OUT_OF_BAND = "oob"

# required parameters, per sections 6.1.1, 6.3.1, and 7
PARAMETERS = %w(oauth_callback oauth_consumer_key oauth_token oauth_signature_method oauth_timestamp oauth_nonce oauth_verifier oauth_version oauth_signature)
PARAMETERS = %w(oauth_callback oauth_consumer_key oauth_token
oauth_signature_method oauth_timestamp oauth_nonce oauth_verifier
oauth_version oauth_signature oauth_body_hash)

# reserved character regexp, per section 5.1
RESERVED_CHARACTERS = /[^a-zA-Z0-9\-\.\_\~]/
@@ -22,4 +22,4 @@ def mock_incoming_request_with_authorize_header(request)
incoming
end
end
end
end
@@ -34,8 +34,9 @@ def parameters_for_signature

unless options[:clobber_request]
params << header_params.to_query
params << request.query_string unless request.query_string.blank?
if request.post? && request.content_type == Mime::Type.lookup("application/x-www-form-urlencoded")
params << request.query_string unless query_string_blank?

if request.post? && request.content_type.to_s.downcase.start_with?("application/x-www-form-urlencoded")
params << request.raw_post
end
end
@@ -9,10 +9,11 @@ def self.proxies(klass)
OAuth::RequestProxy.available_proxies[klass] = self
end

attr_accessor :request, :options
attr_accessor :request, :options, :unsigned_parameters

def initialize(request, options = {})
@request = request
@unsigned_parameters = (options[:unsigned_parameters] || []).map {|param| param.to_s}
@options = options
end

@@ -32,7 +33,7 @@ def oauth_nonce

def oauth_signature
# TODO can this be nil?
parameters['oauth_signature'] || ""
[parameters['oauth_signature']].flatten.first || ""
end

def oauth_signature_method
@@ -75,7 +76,7 @@ def parameters
end

def parameters_for_signature
parameters.reject { |k,v| k == "oauth_signature" }
parameters.reject { |k,v| k == "oauth_signature" || unsigned_parameters.include?(k)}
end

def oauth_parameters
@@ -141,6 +142,14 @@ def oauth_header(options = {})
"OAuth #{realm}#{header_params_str}"
end

def query_string_blank?
if uri = request.request_uri
uri.split('?', 2)[1].nil?
else
request.query_string.blank?
end
end

protected

def header_params
@@ -0,0 +1,55 @@
require 'oauth/request_proxy/base'
require 'curb'
require 'uri'
require 'cgi'

module OAuth::RequestProxy::Curl
class Easy < OAuth::RequestProxy::Base
# Proxy for signing Curl::Easy requests
# Usage example:
# oauth_params = {:consumer => oauth_consumer, :token => access_token}
# req = Curl::Easy.new(uri)
# oauth_helper = OAuth::Client::Helper.new(req, oauth_params.merge(:request_uri => uri))
# req.headers.merge!({"Authorization" => oauth_helper.header})
# req.http_get
# response = req.body_str
proxies ::Curl::Easy

def method
nil
end

def uri
options[:uri].to_s
end

def parameters
if options[:clobber_request]
options[:parameters]
else
post_parameters.merge(query_parameters).merge(options[:parameters] || {})
end
end

private

def query_parameters
query = URI.parse(request.url).query
return(query ? CGI.parse(query) : {})
end

def post_parameters
post_body = {}

# Post params are only used if posting form data
if (request.headers['Content-Type'] && request.headers['Content-Type'].to_s.downcase.start_with?("application/x-www-form-urlencoded"))

request.post_body.split("&").each do |str|
param = str.split("=")
post_body[param[0]] = param[1]
end
end
post_body
end
end
end
@@ -0,0 +1,66 @@
require 'oauth/request_proxy/base'
# em-http also uses adddressable so there is no need to require uri.
require 'em-http'
require 'cgi'

module OAuth::RequestProxy::EventMachine
class HttpRequest < OAuth::RequestProxy::Base

# A Proxy for use when you need to sign EventMachine::HttpClient instances.
# It needs to be called once the client is construct but before data is sent.
# Also see oauth/client/em-http
proxies ::EventMachine::HttpClient

# Request in this con

def method
request.method
end

def uri
request.normalize_uri.to_s
end

def parameters
if options[:clobber_request]
options[:parameters]
else
all_parameters
end
end

protected

def all_parameters
merged_parameters({}, post_parameters, query_parameters, options[:parameters])
end

def query_parameters
CGI.parse(request.normalize_uri.query.to_s)
end

def post_parameters
headers = request.options[:head] || {}
form_encoded = headers['Content-Type'].to_s.downcase.start_with?("application/x-www-form-urlencoded")
if ['POST', 'PUT'].include?(method) && form_encoded
CGI.parse(request.normalize_body.to_s)
else
{}
end
end

def merged_parameters(params, *extra_params)
extra_params.compact.each do |params_pairs|
params_pairs.each_pair do |key, value|
if params.has_key?(key)
params[key] += value
else
params[key] = [value].flatten
end
end
end
params
end

end
end
@@ -6,15 +6,14 @@
module OAuth::RequestProxy::Net
module HTTP
class HTTPRequest < OAuth::RequestProxy::Base
proxies ::Net::HTTPRequest
proxies ::Net::HTTPGenericRequest

def method
request.method
end

def uri
uri = options[:uri]
uri.to_s
options[:uri].to_s
end

def parameters
@@ -25,16 +24,22 @@ def parameters
end
end

def body
request.body
end

private

def all_parameters
request_params = CGI.parse(query_string)
# request_params.each{|k,v| request_params[k] = [nil] if v == []}

if options[:parameters]
options[:parameters].each do |k,v|
if request_params.has_key?(k)
if request_params.has_key?(k) && v
request_params[k] << v
else
request_params[k] = [v].flatten
request_params[k] = [v]
end
end
end
@@ -43,11 +48,14 @@ def all_parameters

def query_string
params = [ query_params, auth_header_params ]
is_form_urlencoded = request['Content-Type'] != nil && request['Content-Type'].downcase == 'application/x-www-form-urlencoded'
params << post_params if method.to_s.upcase == 'POST' && is_form_urlencoded
params << post_params if (method.to_s.upcase == 'POST' || method.to_s.upcase == 'PUT') && form_url_encoded?
params.compact.join('&')
end

def form_url_encoded?
request['Content-Type'] != nil && request['Content-Type'].to_s.downcase.start_with?('application/x-www-form-urlencoded')
end

def query_params
URI.parse(request.path).query
end
@@ -34,7 +34,11 @@ def query_params
end

def request_params
request.params
if request.content_type and request.content_type.to_s.downcase.start_with?("application/x-www-form-urlencoded")
request.POST
else
{}
end
end
end
end
@@ -0,0 +1,53 @@
require 'oauth/request_proxy/base'
require 'typhoeus'
require 'typhoeus/request'
require 'uri'
require 'cgi'

module OAuth::RequestProxy::Typhoeus
class Request < OAuth::RequestProxy::Base
# Proxy for signing Typhoeus::Request requests
# Usage example:
# oauth_params = {:consumer => oauth_consumer, :token => access_token}
# req = Typhoeus::Request.new(uri, options)
# oauth_helper = OAuth::Client::Helper.new(req, oauth_params.merge(:request_uri => uri))
# req.headers.merge!({"Authorization" => oauth_helper.header})
# hydra = Typhoeus::Hydra.new()
# hydra.queue(req)
# hydra.run
# response = req.response
proxies Typhoeus::Request

def method
request.method.to_s.upcase
end

def uri
options[:uri].to_s
end

def parameters
if options[:clobber_request]
options[:parameters]
else
post_parameters.merge(query_parameters).merge(options[:parameters] || {})
end
end

private

def query_parameters
query = URI.parse(request.url).query
query ? CGI.parse(query) : {}
end

def post_parameters
# Post params are only used if posting form data
if method == 'POST'
OAuth::Helper.stringify_keys(request.params || {})
else
{}
end
end
end
end
@@ -10,7 +10,10 @@ def self.available_methods
# Raises UnknownSignatureMethod exception if the signature method is unknown.
def self.build(request, options = {}, &block)
request = OAuth::RequestProxy.proxy(request, options)
klass = available_methods[(request.signature_method || "").downcase]
klass = available_methods[
(request.signature_method ||
((c = request.options[:consumer]) && c.options[:signature_method]) ||
"").downcase]
raise UnknownSignatureMethod, request.signature_method unless klass
klass.new(request, options, &block)
end
@@ -32,6 +35,11 @@ def self.signature_base_string(request, options = {}, &block)
self.build(request, options, &block).signature_base_string
end

# Create the body hash for a request
def self.body_hash(request, options = {}, &block)
self.build(request, options, &block).body_hash
end

class UnknownSignatureMethod < Exception; end
end
end
@@ -10,15 +10,27 @@ class Base
attr_accessor :options
attr_reader :token_secret, :consumer_secret, :request

def self.implements(signature_method)
OAuth::Signature.available_methods[signature_method] = self
def self.implements(signature_method = nil)
return @implements if signature_method.nil?
@implements = signature_method
OAuth::Signature.available_methods[@implements] = self
end

def self.digest_class(digest_class = nil)
return @digest_class if digest_class.nil?
@digest_class = digest_class
end

def self.digest_klass(digest_klass = nil)
return @digest_klass if digest_klass.nil?
@digest_klass = digest_klass
end

def self.hash_class(hash_class = nil)
return @hash_class if hash_class.nil?
@hash_class = hash_class
end

def initialize(request, options = {}, &block)
raise TypeError unless request.kind_of?(OAuth::RequestProxy::Base)
@request = request
@@ -38,7 +50,6 @@ def initialize(request, options = {}, &block)
# presence of :token_secret option will override any Token that's provided
@token_secret = options[:token_secret] if options[:token_secret]


# override secrets based on the values returned from the block (if any)
if block_given?
# consumer secret and token secret need to be looked up based on pieces of the request
@@ -66,6 +77,14 @@ def signature_base_string
request.signature_base_string
end

def body_hash
if self.class.hash_class
Base64.encode64(self.class.hash_class.digest(request.body || '')).chomp.gsub(/\n/,'')
else
nil # no body hash algorithm defined, so don't generate one
end
end

private

def token
@@ -1,12 +1,15 @@
# -*- encoding: utf-8 -*-

require 'oauth/signature/base'
require 'digest/hmac'

module OAuth::Signature::HMAC
class Base < OAuth::Signature::Base

private

def digest
self.class.digest_class.digest(secret, signature_base_string)
self.class.digest_class Object.module_eval("::Digest::#{self.class.digest_klass}")
Digest::HMAC.digest(signature_base_string, secret, self.class.digest_class)
end
end
end
@@ -1,9 +1,8 @@
require 'oauth/signature/hmac/base'
require 'hmac-md5'

module OAuth::Signature::HMAC
class MD5 < Base
implements 'hmac-md5'
digest_class ::HMAC::MD5
digest_class 'MD5'
end
end
@@ -1,9 +1,8 @@
require 'oauth/signature/hmac/base'
require 'hmac-rmd160'

module OAuth::Signature::HMAC
class RMD160 < Base
implements 'hmac-rmd160'
digest_class ::HMAC::RMD160
digest_klass 'RMD160'
end
end
@@ -1,9 +1,9 @@
require 'oauth/signature/hmac/base'
require 'hmac-sha1'

module OAuth::Signature::HMAC
class SHA1 < Base
implements 'hmac-sha1'
digest_class ::HMAC::SHA1
digest_klass 'SHA1'
hash_class ::Digest::SHA1
end
end
@@ -1,9 +1,8 @@
require 'oauth/signature/hmac/base'
require 'hmac-sha2'

module OAuth::Signature::HMAC
class SHA2 < Base
implements 'hmac-sha2'
digest_class ::HMAC::SHA2
digest_klass 'SHA2'
end
end
@@ -9,15 +9,15 @@ def signature
end

def ==(cmp_signature)
signature == escape(cmp_signature)
signature.to_s == cmp_signature.to_s
end

def signature_base_string
secret
end

def secret
escape(super)
super
end
end
end
@@ -4,6 +4,7 @@
module OAuth::Signature::RSA
class SHA1 < OAuth::Signature::Base
implements 'rsa-sha1'
hash_class ::Digest::SHA1

def ==(cmp_signature)
public_key.verify(OpenSSL::Digest::SHA1.new, Base64.decode64(cmp_signature.is_a?(Array) ? cmp_signature.first : cmp_signature), signature_base_string)
@@ -3,19 +3,18 @@ module OAuth
class AccessToken < ConsumerToken
# The less intrusive way. Otherwise, if we are to do it correctly inside consumer,
# we need to restructure and touch more methods: request(), sign!(), etc.
def request(http_method, path, *arguments, &block)
def request(http_method, path, *arguments)
request_uri = URI.parse(path)
site_uri = consumer.uri
is_service_uri_different = (request_uri.absolute? && request_uri != site_uri)
consumer.uri(request_uri) if is_service_uri_different
if block_given?
return super(http_method, path, *arguments, &block)
else
begin
consumer.uri(request_uri) if is_service_uri_different
@response = super(http_method, path, *arguments)
ensure
# NOTE: reset for wholesomeness? meaning that we admit only AccessToken service calls may use different URIs?
# so reset in case consumer is still used for other token-management tasks subsequently?
consumer.uri(site_uri) if is_service_uri_different
end
# NOTE: reset for wholesomeness? meaning that we admit only AccessToken service calls may use different URIs?
# so reset in case consumer is still used for other token-management tasks subsequently?
consumer.uri(site_uri) if is_service_uri_different
@response
end

@@ -24,8 +23,8 @@ def request(http_method, path, *arguments, &block)
# @response = @token.get('/people')
# @response = @token.get('/people', { 'Accept'=>'application/xml' })
#
def get(path, headers = {}, &block)
request(:get, path, headers, &block)
def get(path, headers = {})
request(:get, path, headers)
end

# Make a regular HEAD request using AccessToken
@@ -44,8 +43,8 @@ def head(path, headers = {})
# @response = @token.post('/people', nil, {'Accept' => 'application/xml' })
# @response = @token.post('/people', @person.to_xml, { 'Accept'=>'application/xml', 'Content-Type' => 'application/xml' })
#
def post(path, body = '', headers = {}, &block)
request(:post, path, body, headers, &block)
def post(path, body = '', headers = {})
request(:post, path, body, headers)
end

# Make a regular PUT request using AccessToken
@@ -56,17 +55,17 @@ def post(path, body = '', headers = {}, &block)
# @response = @token.put('/people/123', nil, { 'Accept' => 'application/xml' })
# @response = @token.put('/people/123', @person.to_xml, { 'Accept' => 'application/xml', 'Content-Type' => 'application/xml' })
#
def put(path, body = '', headers = {}, &block)
request(:put, path, body, headers, &block)
def put(path, body = '', headers = {})
request(:put, path, body, headers)
end

# Make a regular DELETE request using AccessToken
#
# @response = @token.delete('/people/123')
# @response = @token.delete('/people/123', { 'Accept' => 'application/xml' })
#
def delete(path, headers = {}, &block)
request(:delete, path, headers, &block)
def delete(path, headers = {})
request(:delete, path, headers)
end
end
end
@@ -21,12 +21,8 @@ def initialize(consumer, token="", secret="")
# @token.request(:get, '/people')
# @token.request(:post, '/people', @person.to_xml, { 'Content-Type' => 'application/xml' })
#
def request(http_method, path, *arguments, &block)
if block_given?
consumer.request(http_method, path, self, {}, *arguments, &block)
else
@response = consumer.request(http_method, path, self, {}, *arguments)
end
def request(http_method, path, *arguments)
@response = consumer.request(http_method, path, self, {}, *arguments)
end

# Sign a request generated elsewhere using Net:HTTP::Post.new or friends

This file was deleted.

@@ -9,11 +9,9 @@
miquire :miku, 'miku'

class Gtk::MessagePicker < Gtk::EventBox
attr_reader :to_a

def initialize(conditions, &block)
conditions = [] unless conditions.is_a? MIKU::List
@to_a = conditions.freeze
super()
@not = (conditions.respond_to?(:car) and (conditions.car == :not))
if(@not)
@@ -27,6 +25,7 @@ def initialize(conditions, &block)
shell.closeup(add_button.center)
exprs.each{|x| add_condition(x) }
add(Gtk::Frame.new.set_border_width(8).set_label_widget(option_widgets).add(shell))
p "#{self}: #{to_a}"
end

def function(new = @function)
@@ -65,19 +64,18 @@ def add_condition(expr = [:==, :user, ''])
pack.add(Gtk::MessagePicker::PickCondition.new(expr, &method(:call))) end
@container.closeup(pack) end

def to_a
result = [@function, *@container.children.map{|x| x.children.last.to_a}].freeze
if(@not)
result = [:not, result].freeze end
result end

private

def call
recalc_to_a
if @changed_hook
@changed_hook.call end end

def recalc_to_a
@to_a = [@function, *@container.children.map{|x| x.children.last.to_a}].freeze
if(@not)
@to_a = [:not, @to_a].freeze end
@to_a end

def gen_add_button
container = Gtk::HBox.new
btn = Gtk::Button.new('条件を追加')
@@ -461,9 +461,15 @@ def execute_unload_hook
def method_missing(method, *args, &proc)
case method.to_s
when /^on_?(.+)$/
<<<<<<< HEAD
add_event($1, &proc)
when /^filter_?(.+)$/
add_event_filter($1, &proc)
=======
add_event($1, &proc)
when /^filter_?(.+)$/
add_event_filter($1, &proc)
>>>>>>> remotes/0.1
when /^hook_?(.+)$/
add_event_hook($1, &proc)
else