oauth-0.4.7/0000755000004100000410000000000012055513522012672 5ustar www-datawww-dataoauth-0.4.7/test/0000755000004100000410000000000012055513522013651 5ustar www-datawww-dataoauth-0.4.7/test/test_access_token.rb0000644000004100000410000000136312055513522017701 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) class TestAccessToken < Test::Unit::TestCase def setup @fake_response = { :user_id => 5734758743895, :oauth_token => "key", :oauth_token_secret => "secret" } # setup a fake req. token. mocking Consumer would be more appropriate... @access_token = OAuth::AccessToken.from_hash( OAuth::Consumer.new("key", "secret", {}), @fake_response ) end def test_provides_response_parameters assert @access_token assert_respond_to @access_token, :params end def test_access_token_makes_non_oauth_response_params_available assert_not_nil @access_token.params[:user_id] assert_equal 5734758743895, @access_token.params[:user_id] end end oauth-0.4.7/test/cases/0000755000004100000410000000000012055513522014747 5ustar www-datawww-dataoauth-0.4.7/test/cases/oauth_case.rb0000644000004100000410000000071712055513522017414 0ustar www-datawww-datarequire 'test/unit' require 'oauth/signature' require 'oauth/request_proxy/mock_request' class OAuthCase < Test::Unit::TestCase # avoid whining about a lack of tests def run(*args) return if @method_name.to_s == "default_test" super end protected # Creates a fake request def request(params={},method='GET',uri="http://photos.example.net/photos") OAuth::RequestProxy.proxy({'parameters'=>params,'method'=>method,'uri'=>uri}) end end oauth-0.4.7/test/cases/spec/0000755000004100000410000000000012055513522015701 5ustar www-datawww-dataoauth-0.4.7/test/cases/spec/1_0-final/0000755000004100000410000000000012055513522017347 5ustar www-datawww-dataoauth-0.4.7/test/cases/spec/1_0-final/test_normalize_request_parameters.rb0000644000004100000410000000562312055513522026734 0ustar www-datawww-datarequire File.expand_path('../../../oauth_case', __FILE__) # See http://oauth.net/core/1.0/#anchor14 # # 9.1.1. Normalize Request Parameters # # The request parameters are collected, sorted and concatenated into a normalized string: # # Parameters in the OAuth HTTP Authorization header excluding the realm parameter. # Parameters in the HTTP POST request body (with a content-type of application/x-www-form-urlencoded). # HTTP GET parameters added to the URLs in the query part (as defined by [RFC3986] section 3). # The oauth_signature parameter MUST be excluded. # # The parameters are normalized into a single string as follows: # # Parameters are sorted by name, using lexicographical byte value ordering. # If two or more parameters share the same name, they are sorted by their value. For example: # # a=1, c=hi%20there, f=25, f=50, f=a, z=p, z=t # Parameters are concatenated in their sorted order into a single string. For each parameter, # the name is separated from the corresponding value by an ‘=’ character (ASCII code 61), even # if the value is empty. Each name-value pair is separated by an ‘&’ character (ASCII code 38). For example: # a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t # class NormalizeRequestParametersTest < OAuthCase def test_parameters_for_signature params={'a'=>1, 'c'=>'hi there', 'f'=>'25', 'f'=>'50', 'f'=>'a', 'z'=>'p', 'z'=>'t'} assert_equal params,request(params).parameters_for_signature end def test_parameters_for_signature_removes_oauth_signature params={'a'=>1, 'c'=>'hi there', 'f'=>'25', 'f'=>'50', 'f'=>'a', 'z'=>'p', 'z'=>'t'} assert_equal params,request(params.merge({'oauth_signature'=>'blalbla'})).parameters_for_signature end def test_spec_example assert_normalized 'a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t', { 'a' => 1, 'c' => 'hi there', 'f' => ['25', '50', 'a'], 'z' => ['p', 't'] } end def test_sorts_parameters_correctly # values for 'f' are scrambled assert_normalized 'a=1&c=hi%20there&f=5&f=70&f=a&z=p&z=t', { 'a' => 1, 'c' => 'hi there', 'f' => ['a', '70', '5'], 'z' => ['p', 't'] } end def test_empty assert_normalized "",{} end # These are from the wiki http://wiki.oauth.net/TestCases # in the section Normalize Request Parameters # Parameters have already been x-www-form-urlencoded (i.e. + = ) def test_wiki1 assert_normalized "name=",{"name"=>nil} end def test_wiki2 assert_normalized "a=b",{'a'=>'b'} end def test_wiki3 assert_normalized "a=b&c=d",{'a'=>'b','c'=>'d'} end def test_wiki4 assert_normalized "a=x%20y&a=x%21y",{'a'=>["x!y","x y"]} end def test_wiki5 assert_normalized "x=a&x%21y=a",{"x!y"=>'a','x'=>'a'} end protected def assert_normalized(expected,params,message=nil) assert_equal expected, normalize_request_parameters(params), message end def normalize_request_parameters(params={}) request(params).normalized_parameters end end oauth-0.4.7/test/cases/spec/1_0-final/test_construct_request_url.rb0000644000004100000410000000463712055513522025423 0ustar www-datawww-datarequire File.expand_path('../../../oauth_case', __FILE__) # See http://oauth.net/core/1.0/#anchor14 # #9.1.2. Construct Request URL # #The Signature Base String includes the request absolute URL, tying the signature to a specific endpoint. The URL used in the Signature Base String MUST include the scheme, authority, and path, and MUST exclude the query and fragment as defined by [RFC3986] section 3. # #If the absolute request URL is not available to the Service Provider (it is always available to the Consumer), it can be constructed by combining the scheme being used, the HTTP Host header, and the relative HTTP request URL. If the Host header is not available, the Service Provider SHOULD use the host name communicated to the Consumer in the documentation or other means. # #The Service Provider SHOULD document the form of URL used in the Signature Base String to avoid ambiguity due to URL normalization. Unless specified, URL scheme and authority MUST be lowercase and include the port number; http default port 80 and https default port 443 MUST be excluded. # #For example, the request: # # HTTP://Example.com:80/resource?id=123 #Is included in the Signature Base String as: # # http://example.com/resource class ConstructRequestUrlTest < OAuthCase def test_from_spec assert_request_url("http://example.com/resource","HTTP://Example.com:80/resource?id=123") end def test_simple_url_with_ending_slash assert_request_url("http://example.com/","http://example.com/") end def test_simple_url_without_ending_slash assert_request_url("http://example.com/","http://example.com") end def test_of_normalized_http assert_request_url("http://example.com/resource","http://example.com/resource") end def test_of_https assert_request_url("https://example.com/resource","HTTPS://Example.com:443/resource?id=123") end def test_of_normalized_https assert_request_url("https://example.com/resource","https://example.com/resource") end def test_of_http_with_non_standard_port assert_request_url("http://example.com:8080/resource","http://example.com:8080/resource") end def test_of_https_with_non_standard_port assert_request_url("https://example.com:8080/resource","https://example.com:8080/resource") end protected def assert_request_url(expected,given,message=nil) assert_equal expected, request({},'GET',given).normalized_uri, message end end oauth-0.4.7/test/cases/spec/1_0-final/test_signature_base_strings.rb0000644000004100000410000000553212055513522025504 0ustar www-datawww-datarequire File.expand_path('../../../oauth_case', __FILE__) # See http://oauth.net/core/1.0/#anchor14 # # 9.1. Signature Base String # # The Signature Base String is a consistent reproducible concatenation of the request elements # into a single string. The string is used as an input in hashing or signing algorithms. The # HMAC-SHA1 signature method provides both a standard and an example of using the Signature # Base String with a signing algorithm to generate signatures. All the request parameters MUST # be encoded as described in Parameter Encoding prior to constructing the Signature Base String. # class SignatureBaseStringTest < OAuthCase def test_A_5_1 parameters={ 'oauth_consumer_key'=>'dpf43f3p2l4k3l03', 'oauth_token'=>'nnch734d00sl2jdk', 'oauth_signature_method'=>'HMAC-SHA1', 'oauth_timestamp'=>'1191242096', 'oauth_nonce'=>'kllo9940pd9333jh', 'oauth_version'=>'1.0', 'file'=>'vacation.jpg', 'size'=>'original' } sbs='GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal' assert_signature_base_string sbs,parameters,'GET',"http://photos.example.net/photos" end # These are from the wiki http://wiki.oauth.net/TestCases # in the section Concatenate Test Elements def test_wiki_1_simple_with_ending_slash parameters={ 'n'=>'v' } sbs='GET&http%3A%2F%2Fexample.com%2F&n%3Dv' assert_signature_base_string sbs,parameters,'GET',"http://example.com/" end def test_wiki_2_simple_without_ending_slash parameters={ 'n'=>'v' } sbs='GET&http%3A%2F%2Fexample.com%2F&n%3Dv' assert_signature_base_string sbs,parameters,'GET',"http://example.com" end def test_wiki_2_request_token parameters={ 'oauth_version'=>'1.0', 'oauth_consumer_key'=>'dpf43f3p2l4k3l03', 'oauth_timestamp'=>'1191242090', 'oauth_nonce'=>'hsu94j3884jdopsl', 'oauth_signature_method'=>'PLAINTEXT', 'oauth_signature'=>'ignored' } sbs='POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0' assert_signature_base_string sbs,parameters,'POST',"https://photos.example.net/request_token" end protected def assert_signature_base_string(expected,params={},method='GET',uri="http://photos.example.net/photos",message="Signature Base String does not match") assert_equal expected, signature_base_string(params,method,uri), message end def signature_base_string(params={},method='GET',uri="http://photos.example.net/photos") request(params,method,uri).signature_base_string end end oauth-0.4.7/test/cases/spec/1_0-final/test_parameter_encodings.rb0000644000004100000410000000412412055513522024745 0ustar www-datawww-datarequire File.expand_path('../../../oauth_case', __FILE__) # See http://oauth.net/core/1.0/#encoding_parameters # # 5.1. Parameter Encoding # # All parameter names and values are escaped using the [RFC3986] percent-encoding (%xx) mechanism. # Characters not in the unreserved character set ([RFC3986] section 2.3) MUST be encoded. Characters # in the unreserved character set MUST NOT be encoded. Hexadecimal characters in encodings MUST be # upper case. Text names and values MUST be encoded as UTF-8 octets before percent-encoding them per [RFC3629]. # # unreserved = ALPHA, DIGIT, '-', '.', '_', '~' # class ParameterEncodingTest < OAuthCase def test_encodings_alpha_num assert_encoding 'abcABC123', 'abcABC123' end def test_encodings_non_escaped assert_encoding '-._~', '-._~' end def test_encodings_percent assert_encoding '%25', '%' end def test_encodings_plus assert_encoding '%2B', '+' end def test_encodings_space assert_encoding '%20', ' ' end def test_encodings_query_param_symbols assert_encoding '%26%3D%2A', '&=*' end def test_encodings_unicode_lf assert_encoding '%0A', unicode_to_utf8('U+000A') end def test_encodings_unicode_space assert_encoding '%20', unicode_to_utf8('U+0020') end def test_encodings_unicode_007f assert_encoding '%7F', unicode_to_utf8('U+007F') end def test_encodings_unicode_0080 assert_encoding '%C2%80', unicode_to_utf8('U+0080') end def test_encoding_unicode_2708 assert_encoding '%E2%9C%88', unicode_to_utf8('U+2708') end def test_encodings_unicode_3001 assert_encoding '%E3%80%81', unicode_to_utf8('U+3001') end protected def unicode_to_utf8(unicode) return unicode if unicode =~ /\A[[:space:]]*\z/m str = '' unicode.scan(/(U\+(?:[[:digit:][:xdigit:]]{4,5}|10[[:digit:][:xdigit:]]{4})|.)/mu) do c = $1 if c =~ /^U\+/ str << [c[2..-1].hex].pack('U*') else str << c end end str end def assert_encoding(expected, given, message = nil) assert_equal expected, OAuth::Helper.escape(given), message end end oauth-0.4.7/test/test_oauth_helper.rb0000644000004100000410000000726112055513522017722 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) class TestOAuthHelper < Test::Unit::TestCase def test_parse_valid_header header = 'OAuth ' \ 'realm="http://example.com/method", ' \ 'oauth_consumer_key="vince_clortho", ' \ 'oauth_token="token_value", ' \ 'oauth_signature_method="HMAC-SHA1", ' \ 'oauth_signature="signature_here", ' \ 'oauth_timestamp="1240004133", oauth_nonce="nonce", ' \ 'oauth_version="1.0" ' params = OAuth::Helper.parse_header(header) assert_equal "http://example.com/method", params['realm'] assert_equal "vince_clortho", params['oauth_consumer_key'] assert_equal "token_value", params['oauth_token'] assert_equal "HMAC-SHA1", params['oauth_signature_method'] assert_equal "signature_here", params['oauth_signature'] assert_equal "1240004133", params['oauth_timestamp'] assert_equal "nonce", params['oauth_nonce'] assert_equal "1.0", params['oauth_version'] end def test_parse_header_ill_formed header = "OAuth garbage" assert_raise OAuth::Problem do OAuth::Helper.parse_header(header) end end def test_parse_header_contains_equals header = 'OAuth ' \ 'realm="http://example.com/method", ' \ 'oauth_consumer_key="vince_clortho", ' \ 'oauth_token="token_value", ' \ 'oauth_signature_method="HMAC-SHA1", ' \ 'oauth_signature="signature_here_with_=", ' \ 'oauth_timestamp="1240004133", oauth_nonce="nonce", ' \ 'oauth_version="1.0" ' assert_raise OAuth::Problem do OAuth::Helper.parse_header(header) end end def test_parse_valid_header_with_and_signs header = 'OAuth ' \ 'realm="http://example.com/method"&' \ 'oauth_consumer_key="vince_clortho"&' \ 'oauth_token="token_value"&' \ 'oauth_signature_method="HMAC-SHA1"&' \ 'oauth_signature="signature_here"&' \ 'oauth_timestamp="1240004133"&oauth_nonce="nonce"&' \ 'oauth_version="1.0"' params = OAuth::Helper.parse_header(header) assert_equal "http://example.com/method", params['realm'] assert_equal "vince_clortho", params['oauth_consumer_key'] assert_equal "token_value", params['oauth_token'] assert_equal "HMAC-SHA1", params['oauth_signature_method'] assert_equal "signature_here", params['oauth_signature'] assert_equal "1240004133", params['oauth_timestamp'] assert_equal "nonce", params['oauth_nonce'] assert_equal "1.0", params['oauth_version'] end def test_normalize params = { 'oauth_nonce' => 'nonce', 'weight' => { :value => "65" }, 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => "1240004133", 'oauth_consumer_key' => 'vince_clortho', 'oauth_token' => 'token_value', 'oauth_version' => "1.0" } assert_equal("oauth_consumer_key=vince_clortho&oauth_nonce=nonce&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1240004133&oauth_token=token_value&oauth_version=1.0&weight%5Bvalue%5D=65", OAuth::Helper.normalize(params)) end def test_normalize_nested_query assert_equal([], OAuth::Helper.normalize_nested_query({})) assert_equal(["foo=bar"], OAuth::Helper.normalize_nested_query({:foo => 'bar'})) assert_equal(["prefix%5Bfoo%5D=bar"], OAuth::Helper.normalize_nested_query({:foo => 'bar'}, 'prefix')) assert_equal(["prefix%5Buser%5D%5Bage%5D=12", "prefix%5Buser%5D%5Bdate%5D=2011-10-05", "prefix%5Buser%5D%5Btwitter_id%5D=123"], OAuth::Helper.normalize_nested_query({:user => {:twitter_id => 123, :date => '2011-10-05', :age => 12}}, 'prefix')) end end oauth-0.4.7/test/test_net_http_client.rb0000644000004100000410000004341212055513522020424 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) class NetHTTPClientTest < Test::Unit::TestCase def setup @consumer = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237') @token = OAuth::Token.new('token_411a7f', '3196ffd991c8ebdb') @request_uri = URI.parse('http://example.com/test?key=value') @request_parameters = { 'key' => 'value' } @nonce = 225579211881198842005988698334675835446 @timestamp = "1199645624" @http = Net::HTTP.new(@request_uri.host, @request_uri.port) end def test_that_using_auth_headers_on_get_requests_works request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s) request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'GET', request.method assert_equal '/test?key=value', request.path correct_sorted_params = "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"" auth_intro, auth_params = request['authorization'].split(' ', 2) assert_equal auth_intro, 'OAuth' assert_matching_headers correct_sorted_params, request['authorization'] end def test_that_using_auth_headers_on_get_requests_works_with_plaintext require 'oauth/signature/plaintext' c = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237',{ :signature_method => 'PLAINTEXT' }) request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s) request.oauth!(@http, c, @token, {:nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'}) assert_equal 'GET', request.method assert_equal '/test?key=value', request.path assert_matching_headers "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"PLAINTEXT\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"", request['authorization'] end def test_that_using_auth_headers_on_post_requests_works request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( @request_parameters ) request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_equal 'key=value', request.body correct_sorted_params = "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"" assert_matching_headers correct_sorted_params, request['authorization'] end def test_that_using_auth_headers_on_post_requests_with_data_works request = Net::HTTP::Post.new(@request_uri.path) request.body = "data" request.content_type = 'text/ascii' request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_equal 'data', request.body assert_equal 'text/ascii', request.content_type assert_matching_headers "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_body_hash=\"oXyaqmHoChv3HQ2FCvTluqmAC70%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"0DA6pGTapdHSqC15RZelY5rNLDw%3D\", oauth_version=\"1.0\"", request['authorization'] end def test_that_body_hash_is_obmitted_when_no_algorithm_is_defined request = Net::HTTP::Post.new(@request_uri.path) request.body = "data" request.content_type = 'text/ascii' request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp, :signature_method => 'plaintext'}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_equal 'data', request.body assert_equal 'text/ascii', request.content_type assert_matching_headers "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"plaintext\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"", request['authorization'] end def test_that_version_is_added_to_existing_user_agent request = Net::HTTP::Post.new(@request_uri.path) request['User-Agent'] = "MyApp" request.set_form_data( @request_parameters ) request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal "MyApp (OAuth gem v#{OAuth::VERSION})", request['User-Agent'] end def test_that_version_is_set_when_no_user_agent request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( @request_parameters ) request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal "OAuth gem v#{OAuth::VERSION}", request['User-Agent'] end def test_that_using_get_params_works request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s) request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp}) assert_equal 'GET', request.method uri = URI.parse(request.path) assert_equal '/test', uri.path assert_equal nil, uri.fragment assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=1oO2izFav1GP4kEH2EskwXkCRFg%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join("&") assert_equal nil, request['authorization'] end def test_that_using_get_params_works_with_plaintext request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s) request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'}) assert_equal 'GET', request.method uri = URI.parse(request.path) assert_equal '/test', uri.path assert_equal nil, uri.fragment assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=5888bf0345e5d237%263196ffd991c8ebdb&oauth_signature_method=PLAINTEXT&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join("&") assert_equal nil, request['authorization'] end def test_that_using_post_params_works request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( @request_parameters ) request.oauth!(@http, @consumer, @token, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_match /key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3[Dd]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0/, request.body.split("&").sort.join("&") assert_equal nil, request['authorization'] end def test_that_using_post_params_works_with_plaintext request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( @request_parameters ) request.oauth!(@http, @consumer, @token, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=5888bf0345e5d237%263196ffd991c8ebdb&oauth_signature_method=PLAINTEXT&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", request.body.split("&").sort.join("&") assert_equal nil, request['authorization'] end def test_that_using_post_body_works request = Net::HTTP::Post.new(@request_uri.path) request['content-type'] = 'application/x-www-form-urlencoded' request.body = 'this is a test of the emergency broad cast system. This is only a test.' request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_match /OAuth oauth_consumer_key="consumer_key_86cad9", oauth_nonce="225579211881198842005988698334675835446", oauth_signature="%2[fF]DMMBOJzQ6JmEaXlAXDLGtD1z2I%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1199645624", oauth_token="token_411a7f", oauth_version="1.0"/, request['authorization'].split("&").sort.join("&") # assert_equal nil, request['authorization'] end def test_that_using_post_with_uri_params_works request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s) request.set_form_data( {} ) # just to make sure we have a correct mime type and thus no body hash request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method uri = URI.parse(request.path) assert_equal '/test', uri.path assert_equal nil, uri.fragment assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&') assert_equal "", request.body assert_equal nil, request['authorization'] end def test_that_using_post_with_uri_and_form_params_works request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s) request.set_form_data( { 'key2' => 'value2' } ) request.oauth!(@http, @consumer, @token, {:scheme => :query_string, :nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method uri = URI.parse(request.path) assert_equal '/test', uri.path assert_equal nil, uri.fragment assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=4kSU8Zd1blWo3W6qJH7eaRTMkg0%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&') assert_equal "key2=value2", request.body assert_equal nil, request['authorization'] end def test_that_using_post_with_uri_and_data_works request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s) request.body = "data" request.content_type = 'text/ascii' request.oauth!(@http, @consumer, @token, {:scheme => :query_string, :nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method uri = URI.parse(request.path) assert_equal '/test', uri.path assert_equal nil, uri.fragment assert_equal "data", request.body assert_equal 'text/ascii', request.content_type assert_equal "key=value&oauth_body_hash=oXyaqmHoChv3HQ2FCvTluqmAC70%3D&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=MHRKU42iVHU4Ke9kBUDa9Zw6IAM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&') assert_equal nil, request['authorization'] end def test_example_from_specs consumer=OAuth::Consumer.new("dpf43f3p2l4k3l03","kd94hf93k423kf44") token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00') request_uri = URI.parse('http://photos.example.net/photos?file=vacation.jpg&size=original') nonce = 'kllo9940pd9333jh' timestamp = "1191242096" http = Net::HTTP.new(request_uri.host, request_uri.port) request = Net::HTTP::Get.new(request_uri.path + "?" + request_uri.query) signature_base_string=request.signature_base_string(http, consumer, token, {:nonce => nonce, :timestamp => timestamp}) assert_equal 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal',signature_base_string # request = Net::HTTP::Get.new(request_uri.path + "?" + request_uri.query) request.oauth!(http, consumer, token, {:nonce => nonce, :timestamp => timestamp, :realm=>"http://photos.example.net/"}) assert_equal 'GET', request.method correct_sorted_params = 'oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_token="nnch734d00sl2jdk", oauth_timestamp="1191242096", oauth_consumer_key="dpf43f3p2l4k3l03", oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", oauth_version="1.0"'.split(', ').sort correct_sorted_params.unshift 'OAuth realm="http://photos.example.net/"' assert_equal correct_sorted_params, request['authorization'].split(', ').sort end def test_step_by_step_token_request token_response = "oauth_token=requestkey&oauth_token_secret=requestsecret" stub_request(:get, %r{http://term\.ie/oauth/example/request_token\.php(\?.*)?}).to_return(:body => token_response) consumer=OAuth::Consumer.new( "key", "secret") request_uri = URI.parse('http://term.ie/oauth/example/request_token.php') nonce = rand(2**128).to_s timestamp = Time.now.to_i.to_s http = Net::HTTP.new(request_uri.host, request_uri.port) request = Net::HTTP::Get.new(request_uri.path) signature_base_string=request.signature_base_string(http, consumer, nil, {:scheme=>:query_string,:nonce => nonce, :timestamp => timestamp}) assert_equal "GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D#{nonce}%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D#{timestamp}%26oauth_version%3D1.0",signature_base_string # request = Net::HTTP::Get.new(request_uri.path) request.oauth!(http, consumer, nil, {:scheme=>:query_string,:nonce => nonce, :timestamp => timestamp}) assert_equal 'GET', request.method assert_nil request.body assert_nil request['authorization'] # assert_equal 'OAuth oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_token="", oauth_timestamp="'+timestamp+'", oauth_consumer_key="key", oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", oauth_version="1.0"', request['authorization'] response=http.request(request) assert_equal "200",response.code # assert_equal request['authorization'],response.body assert_equal token_response, response.body end def test_that_put_bodies_signed request = Net::HTTP::Put.new(@request_uri.path) request.body = "baz" request["Content-Type"] = "application/xml" signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp }) assert_equal "PUT&http%3A%2F%2Fexample.com%2Ftest&oauth_body_hash%3DDvAa1AWdFoH9K%252B%252F2AHm3f6wH27k%253D%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string end def test_that_put_bodies_not_signed_even_if_form_urlencoded request = Net::HTTP::Put.new(@request_uri.path) request.set_form_data( { 'key2' => 'value2' } ) signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp }) assert_equal "PUT&http%3A%2F%2Fexample.com%2Ftest&key2%3Dvalue2%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string end def test_that_post_bodies_signed_if_form_urlencoded request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( { 'key2' => 'value2' } ) signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp }) assert_equal "POST&http%3A%2F%2Fexample.com%2Ftest&key2%3Dvalue2%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string end def test_that_post_bodies_signed_if_other_content_type request = Net::HTTP::Post.new(@request_uri.path) request.body = "baz" request["Content-Type"] = "application/xml" signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp }) assert_equal "POST&http%3A%2F%2Fexample.com%2Ftest&oauth_body_hash%3DDvAa1AWdFoH9K%252B%252F2AHm3f6wH27k%253D%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string end def test_that_site_address_is_not_modified_in_place options = { :site => 'http://twitter.com', :request_endpoint => 'http://api.twitter.com' } request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s) request.oauth!(@http, @consumer, @token, options) assert_equal "http://twitter.com", options[:site] assert_equal "http://api.twitter.com", options[:request_endpoint] end protected def request_parameters_to_s @request_parameters.map { |k,v| "#{k}=#{v}" }.join("&") end end oauth-0.4.7/test/test_rack_request_proxy.rb0000644000004100000410000000342412055513522021171 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'oauth/request_proxy/rack_request' require 'rack/request' require 'rack/mock' class RackRequestProxyTest < Test::Unit::TestCase def test_that_proxy_simple_get_request_works request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/test?key=value')) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'GET', request_proxy.method end def test_that_proxy_simple_post_request_works request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/test', :method => 'POST')) params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end def test_that_proxy_post_and_get_request_works request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/test?key=value', :method => 'POST', :input => 'key2=value2')) params = {'key2' => 'value2'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => params}) expected_parameters = {'key' => 'value', 'key2' => 'value2'} assert_equal expected_parameters, request_proxy.parameters assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end end oauth-0.4.7/test/test_consumer.rb0000644000004100000410000002014612055513522017073 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'mocha' require 'stringio' # This performs testing against Andy Smith's test server http://term.ie/oauth/example/ # Thanks Andy. # This also means you have to be online to be able to run these. class ConsumerTest < Test::Unit::TestCase def setup @consumer=OAuth::Consumer.new( 'consumer_key_86cad9', '5888bf0345e5d237', { :site=>"http://blabla.bla", :proxy=>"http://user:password@proxy.bla:8080", :request_token_path=>"/oauth/example/request_token.php", :access_token_path=>"/oauth/example/access_token.php", :authorize_path=>"/oauth/example/authorize.php", :scheme=>:header, :http_method=>:get }) @token = OAuth::ConsumerToken.new(@consumer,'token_411a7f', '3196ffd991c8ebdb') @request_uri = URI.parse('http://example.com/test?key=value') @request_parameters = { 'key' => 'value' } @nonce = 225579211881198842005988698334675835446 @timestamp = "1199645624" @consumer.http=Net::HTTP.new(@request_uri.host, @request_uri.port) end def test_initializer assert_equal "consumer_key_86cad9",@consumer.key assert_equal "5888bf0345e5d237",@consumer.secret assert_equal "http://blabla.bla",@consumer.site assert_equal "http://user:password@proxy.bla:8080",@consumer.proxy assert_equal "/oauth/example/request_token.php",@consumer.request_token_path assert_equal "/oauth/example/access_token.php",@consumer.access_token_path assert_equal "http://blabla.bla/oauth/example/request_token.php",@consumer.request_token_url assert_equal "http://blabla.bla/oauth/example/access_token.php",@consumer.access_token_url assert_equal "http://blabla.bla/oauth/example/authorize.php",@consumer.authorize_url assert_equal :header,@consumer.scheme assert_equal :get,@consumer.http_method end def test_defaults @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://twitter.com" }) assert_equal "key",@consumer.key assert_equal "secret",@consumer.secret assert_equal "http://twitter.com",@consumer.site assert_nil @consumer.proxy assert_equal "/oauth/request_token",@consumer.request_token_path assert_equal "/oauth/access_token",@consumer.access_token_path assert_equal "http://twitter.com/oauth/request_token",@consumer.request_token_url assert_equal "http://twitter.com/oauth/access_token",@consumer.access_token_url assert_equal "http://twitter.com/oauth/authorize",@consumer.authorize_url assert_equal :header,@consumer.scheme assert_equal :post,@consumer.http_method end def test_site_without_path @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://twitter.com" }) request = stub(:oauth! => nil) http = stub(:request => stub(:to_hash => {})) Net::HTTP::Get.expects(:new).with('/people', {}).returns(request) @consumer.expects(:create_http).returns(http) @consumer.request(:get, '/people', nil, {}) end def test_site_with_path @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://identi.ca/api" }) request = stub(:oauth! => nil) http = stub(:request => stub(:to_hash => {})) Net::HTTP::Get.expects(:new).with('/api/people', {}).returns(request) @consumer.expects(:create_http).returns(http) @consumer.request(:get, '/people', nil, {}) end def test_post_of_nested_params_maintains_nesting @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://twitter.com" }) request = @consumer.create_signed_request( :post, '/people', nil, {}, { :key => { :subkey => 'value' } }) assert_equal 'key%5Bsubkey%5D=value', request.body assert_equal request.content_type, 'application/x-www-form-urlencoded' end def test_override_paths @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://twitter.com", :request_token_url=>"http://oauth.twitter.com/request_token", :access_token_url=>"http://oauth.twitter.com/access_token", :authorize_url=>"http://site.twitter.com/authorize" }) assert_equal "key",@consumer.key assert_equal "secret",@consumer.secret assert_equal "http://twitter.com",@consumer.site assert_equal "/oauth/request_token",@consumer.request_token_path assert_equal "/oauth/access_token",@consumer.access_token_path assert_equal "http://oauth.twitter.com/request_token",@consumer.request_token_url assert_equal "http://oauth.twitter.com/access_token",@consumer.access_token_url assert_equal "http://site.twitter.com/authorize",@consumer.authorize_url assert_equal :header,@consumer.scheme assert_equal :post,@consumer.http_method end def test_that_token_response_should_be_uri_parameter_format_as_default @consumer.expects(:request).returns(create_stub_http_response("oauth_token=token&oauth_token_secret=secret")) hash = @consumer.token_request(:get, "") assert_equal "token", hash[:oauth_token] assert_equal "secret", hash[:oauth_token_secret] end def test_can_provided_a_block_to_interpret_token_response @consumer.expects(:request).returns(create_stub_http_response) hash = @consumer.token_request(:get, '') {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }} assert_equal 'token', hash[:oauth_token] assert_equal 'secret', hash[:oauth_token_secret] end def test_token_request_follows_redirect redirect_url = @request_uri.clone redirect_url.path = "/oauth/example/request_token_redirect.php" stub_request(:get, /.*#{@request_uri.path}/).to_return(:status => 301, :headers => {'Location' => redirect_url.to_s}) stub_request(:get, /.*#{redirect_url.path}/).to_return(:body => "oauth_token=token&oauth_token_secret=secret") hash = @consumer.token_request(:get, @request_uri.path) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }} assert_equal 'token', hash[:oauth_token] assert_equal 'secret', hash[:oauth_token_secret] end def test_that_can_provide_a_block_to_interpret_a_request_token_response @consumer.expects(:request).returns(create_stub_http_response) token = @consumer.get_request_token {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }} assert_equal 'token', token.token assert_equal 'secret', token.secret end def test_that_block_is_not_mandatory_for_getting_an_access_token stub_token = mock @consumer.expects(:request).returns(create_stub_http_response("oauth_token=token&oauth_token_secret=secret")) token = @consumer.get_access_token(stub_token) assert_equal 'token', token.token assert_equal 'secret', token.secret end def test_that_can_provide_a_block_to_interpret_an_access_token_response stub_token = mock @consumer.expects(:request).returns(create_stub_http_response) token = @consumer.get_access_token(stub_token) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }} assert_equal 'token', token.token assert_equal 'secret', token.secret end def test_that_not_setting_ignore_callback_will_include_oauth_callback_in_request_options request_options = {} @consumer.stubs(:request).returns(create_stub_http_response) @consumer.get_request_token(request_options) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }} assert_equal 'oob', request_options[:oauth_callback] end def test_that_setting_ignore_callback_will_exclude_oauth_callback_in_request_options request_options = { :exclude_callback=> true } @consumer.stubs(:request).returns(create_stub_http_response) @consumer.get_request_token(request_options) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }} assert_nil request_options[:oauth_callback] end private def create_stub_http_response expected_body=nil stub_http_response = stub stub_http_response.stubs(:code).returns(200) stub_http_response.stubs(:body).tap {|expectation| expectation.returns(expected_body) unless expected_body.nil? } return stub_http_response end end oauth-0.4.7/test/test_hmac_sha1.rb0000644000004100000410000000175312055513522017067 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) class TestSignatureHmacSha1 < Test::Unit::TestCase def test_that_hmac_sha1_implements_hmac_sha1 assert OAuth::Signature.available_methods.include?('hmac-sha1') end def test_that_get_request_from_oauth_test_cases_produces_matching_signature request = Net::HTTP::Get.new('/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1') consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03', 'kd94hf93k423kf44') token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00') signature = OAuth::Signature.sign(request, { :consumer => consumer, :token => token, :uri => 'http://photos.example.net/photos' } ) assert_equal 'tR3+Ty81lMeYAr/Fid0kMTYa/WM=', signature end end oauth-0.4.7/test/test_helper.rb0000644000004100000410000000225212055513522016515 0ustar www-datawww-datarequire 'test/unit' require 'rubygems' $LOAD_PATH << File.dirname(__FILE__) + '/../lib/' require 'oauth' require 'mocha' require 'stringio' require 'webmock' class Test::Unit::TestCase include WebMock::API def assert_matching_headers(expected, actual) # transform into sorted arrays auth_intro, auth_params = actual.split(' ', 2) assert_equal auth_intro, 'OAuth' expected = expected.split(/(,|\s)/).reject {|v| v == '' || v =~ /^[\,\s]+/}.sort auth_params = auth_params.split(/(,|\s)/).reject {|v| v == '' || v =~ /^[\,\s]+/}.sort assert_equal expected, auth_params end def stub_test_ie stub_request(:any, "http://term.ie/oauth/example/request_token.php").to_return(:body => "oauth_token=requestkey&oauth_token_secret=requestsecret") stub_request(:post, "http://term.ie/oauth/example/access_token.php").to_return(:body => "oauth_token=accesskey&oauth_token_secret=accesssecret") stub_request(:get, %r{http://term\.ie/oauth/example/echo_api\.php\?.+}).to_return(lambda {|request| {:body => request.uri.query}}) stub_request(:post, "http://term.ie/oauth/example/echo_api.php").to_return(lambda {|request| {:body => request.body}}) end end oauth-0.4.7/test/test_typhoeus_request_proxy.rb0000644000004100000410000000672712055513522022142 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) begin require 'oauth/request_proxy/typhoeus_request' require 'typhoeus' class TyphoeusRequestProxyTest < Test::Unit::TestCase def test_that_proxy_simple_get_request_works request = ::Typhoeus::Request.new('/test?key=value') request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'GET', request_proxy.method end def test_that_proxy_simple_post_request_works_with_arguments request = Typhoeus::Request.new('/test', :method => :post) params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_post_request_works_with_form_data request = Typhoeus::Request.new('/test', :method => :post, :params => {'key' => 'value'}, :headers => {'Content-Type' => 'application/x-www-form-urlencoded'}) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_put_request_works_with_arguments request = Typhoeus::Request.new('/test', :method => :put) params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'PUT', request_proxy.method end def test_that_proxy_simple_put_request_works_with_form_data request = Typhoeus::Request.new('/test', :method => :put, :params => {'key' => 'value'}) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'PUT', request_proxy.method end def test_that_proxy_post_request_works_with_mixed_parameter_sources request = Typhoeus::Request.new('/test?key=value', :method => :post, :params => {'key2' => 'value2'}, :headers => {'Content-Type' => 'application/x-www-form-urlencoded'}) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}}) expected_parameters = {'key' => ['value'], 'key2' => 'value2', 'key3' => 'value3'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end end rescue LoadError => e warn "! problem loading typhoeus, skipping these tests: #{e}" end oauth-0.4.7/test/keys/0000755000004100000410000000000012055513522014624 5ustar www-datawww-dataoauth-0.4.7/test/keys/rsa.cert0000644000004100000410000000116612055513522016274 0ustar www-datawww-data-----BEGIN CERTIFICATE----- MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0 IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3 DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d 4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J -----END CERTIFICATE-----oauth-0.4.7/test/keys/rsa.pem0000644000004100000410000000162312055513522016116 0ustar www-datawww-data-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY-----oauth-0.4.7/test/test_curb_request_proxy.rb0000644000004100000410000000603712055513522021207 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) begin require 'oauth/request_proxy/curb_request' require 'curb' class CurbRequestProxyTest < Test::Unit::TestCase def test_that_proxy_simple_get_request_works request = Curl::Easy.new('/test?key=value') request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri end def test_that_proxy_simple_post_request_works_with_arguments request = Curl::Easy.new('/test') params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri end def test_that_proxy_simple_post_request_works_with_form_data request = Curl::Easy.new('/test') request.post_body = 'key=value' request.headers['Content-Type'] = 'application/x-www-form-urlencoded' request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri end def test_that_proxy_simple_put_request_works_with_arguments request = Curl::Easy.new('/test') params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => 'value'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri end def test_that_proxy_simple_put_request_works_with_form_data request = Curl::Easy.new('/test') request.post_body = 'key=value' request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'}) expected_parameters = {} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri end def test_that_proxy_post_request_works_with_mixed_parameter_sources request = Curl::Easy.new('/test?key=value') request.post_body = 'key2=value2' request.headers['Content-Type'] = 'application/x-www-form-urlencoded' request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}}) expected_parameters = {'key' => ['value'], 'key2' => 'value2', 'key3' => 'value3'} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri end end rescue LoadError => e warn "! problems loading curb, skipping these tests: #{e}" end oauth-0.4.7/test/test_signature_plain_text.rb0000644000004100000410000000334412055513522021471 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'oauth/signature/plaintext' class TestSignaturePlaintext < Test::Unit::TestCase def test_that_plaintext_implements_plaintext assert OAuth::Signature.available_methods.include?('plaintext') end def test_that_get_request_from_oauth_test_cases_produces_matching_signature request = Net::HTTP::Get.new('/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_signature=kd94hf93k423kf44%26&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=PLAINTEXT') consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03','kd94hf93k423kf44') token = OAuth::Token.new('nnch734d00sl2jdk', nil) assert OAuth::Signature.verify(request, { :consumer => consumer, :token => token, :uri => 'http://photos.example.net/photos' } ) end def test_that_get_request_from_oauth_test_cases_produces_matching_signature_part_two request = Net::HTTP::Get.new('/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_signature=kd94hf93k423kf44%26pfkkdhi9sl3r4s00&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=PLAINTEXT') consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03','kd94hf93k423kf44') token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00') assert OAuth::Signature.verify(request, { :consumer => consumer, :token => token, :uri => 'http://photos.example.net/photos' } ) end end oauth-0.4.7/test/test_server.rb0000644000004100000410000000273012055513522016545 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'oauth/server' class ServerTest < Test::Unit::TestCase def setup @server=OAuth::Server.new "http://test.com" end def test_default_paths assert_equal "/oauth/request_token",@server.request_token_path assert_equal "/oauth/authorize",@server.authorize_path assert_equal "/oauth/access_token",@server.access_token_path end def test_default_urls assert_equal "http://test.com/oauth/request_token",@server.request_token_url assert_equal "http://test.com/oauth/authorize",@server.authorize_url assert_equal "http://test.com/oauth/access_token",@server.access_token_url end def test_generate_consumer_credentials consumer=@server.generate_consumer_credentials assert_not_nil consumer.key assert_not_nil consumer.secret end def test_create_consumer @consumer=@server.create_consumer assert_not_nil @consumer assert_not_nil @consumer.key assert_not_nil @consumer.secret assert_equal "http://test.com",@consumer.site assert_equal "/oauth/request_token",@consumer.request_token_path assert_equal "/oauth/authorize",@consumer.authorize_path assert_equal "/oauth/access_token",@consumer.access_token_path assert_equal "http://test.com/oauth/request_token",@consumer.request_token_url assert_equal "http://test.com/oauth/authorize",@consumer.authorize_url assert_equal "http://test.com/oauth/access_token",@consumer.access_token_url end end oauth-0.4.7/test/integration/0000755000004100000410000000000012055513522016174 5ustar www-datawww-dataoauth-0.4.7/test/integration/consumer_test.rb0000644000004100000410000003460012055513522021416 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) module Integration class ConsumerTest < Test::Unit::TestCase def setup @consumer=OAuth::Consumer.new( 'consumer_key_86cad9', '5888bf0345e5d237', { :site=>"http://blabla.bla", :proxy=>"http://user:password@proxy.bla:8080", :request_token_path=>"/oauth/example/request_token.php", :access_token_path=>"/oauth/example/access_token.php", :authorize_path=>"/oauth/example/authorize.php", :scheme=>:header, :http_method=>:get }) @token = OAuth::ConsumerToken.new(@consumer,'token_411a7f', '3196ffd991c8ebdb') @request_uri = URI.parse('http://example.com/test?key=value') @request_parameters = { 'key' => 'value' } @nonce = 225579211881198842005988698334675835446 @timestamp = "1199645624" @consumer.http=Net::HTTP.new(@request_uri.host, @request_uri.port) end def test_that_signing_auth_headers_on_get_requests_works request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s) @token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'GET', request.method assert_equal '/test?key=value', request.path assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort end def test_that_setting_signature_method_on_consumer_effects_signing require 'oauth/signature/plaintext' request = Net::HTTP::Get.new(@request_uri.path) consumer = @consumer.dup consumer.options[:signature_method] = 'PLAINTEXT' token = OAuth::ConsumerToken.new(consumer, 'token_411a7f', '3196ffd991c8ebdb') token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp}) assert_no_match( /oauth_signature_method="HMAC-SHA1"/, request['authorization']) assert_match( /oauth_signature_method="PLAINTEXT"/, request['authorization']) end def test_that_setting_signature_method_on_consumer_effects_signature_base_string require 'oauth/signature/plaintext' request = Net::HTTP::Get.new(@request_uri.path) consumer = @consumer.dup consumer.options[:signature_method] = 'PLAINTEXT' request = Net::HTTP::Get.new('/') signature_base_string = consumer.signature_base_string(request) assert_no_match( /HMAC-SHA1/, signature_base_string) assert_equal( "#{consumer.secret}&", signature_base_string) end def test_that_plaintext_signature_works # Invalid test because server expects double-escaped signature require 'oauth/signature/plaintext' # consumer = OAuth::Consumer.new("key", "secret", # :site => "http://term.ie", :signature_method => 'PLAINTEXT') # access_token = OAuth::AccessToken.new(consumer, 'accesskey', 'accesssecret') # response = access_token.get("/oauth/example/echo_api.php?echo=hello") # assert_equal 'echo=hello', response.body end def test_that_signing_auth_headers_on_post_requests_works request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( @request_parameters ) @token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp}) # assert_equal "",request.oauth_helper.signature_base_string assert_equal 'POST', request.method assert_equal '/test', request.path assert_equal 'key=value', request.body assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort end def test_that_signing_post_params_works request = Net::HTTP::Post.new(@request_uri.path) request.set_form_data( @request_parameters ) @token.sign!(request, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_match /key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3[Dd]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0/, request.body.split("&").sort.join("&") assert_equal nil, request['authorization'] end def test_that_using_auth_headers_on_get_on_create_signed_requests_works request=@consumer.create_signed_request(:get,@request_uri.path+ "?" + request_parameters_to_s,@token,{:nonce => @nonce, :timestamp => @timestamp},@request_parameters) assert_equal 'GET', request.method assert_equal '/test?key=value', request.path assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort end def test_that_using_auth_headers_on_post_on_create_signed_requests_works request=@consumer.create_signed_request(:post,@request_uri.path,@token,{:nonce => @nonce, :timestamp => @timestamp},@request_parameters,{}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_equal 'key=value', request.body assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort end def test_that_signing_post_params_works_2 request=@consumer.create_signed_request(:post,@request_uri.path,@token,{:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp},@request_parameters,{}) assert_equal 'POST', request.method assert_equal '/test', request.path assert_match /key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3[Dd]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0/, request.body.split("&").sort.join("&") assert_equal nil, request['authorization'] end def test_step_by_step_token_request stub_test_ie @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://term.ie", :request_token_path=>"/oauth/example/request_token.php", :access_token_path=>"/oauth/example/access_token.php", :authorize_path=>"/oauth/example/authorize.php", :scheme=>:header }) options={:nonce=>'nonce',:timestamp=>Time.now.to_i.to_s} request = Net::HTTP::Get.new("/oauth/example/request_token.php") signature_base_string=@consumer.signature_base_string(request,nil,options) assert_equal "GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D#{options[:nonce]}%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D#{options[:timestamp]}%26oauth_version%3D1.0",signature_base_string @consumer.sign!(request, nil,options) assert_equal 'GET', request.method assert_equal nil, request.body response=@consumer.http.request(request) assert_equal "200",response.code assert_equal "oauth_token=requestkey&oauth_token_secret=requestsecret",response.body end def test_get_token_sequence stub_test_ie @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://term.ie", :request_token_path=>"/oauth/example/request_token.php", :access_token_path=>"/oauth/example/access_token.php", :authorize_path=>"/oauth/example/authorize.php" }) assert_equal "http://term.ie/oauth/example/request_token.php",@consumer.request_token_url assert_equal "http://term.ie/oauth/example/access_token.php",@consumer.access_token_url assert !@consumer.request_token_url?, "Should not use fully qualified request token url" assert !@consumer.access_token_url?, "Should not use fully qualified access token url" assert !@consumer.authorize_url?, "Should not use fully qualified url" @request_token=@consumer.get_request_token assert_not_nil @request_token assert_equal "requestkey",@request_token.token assert_equal "requestsecret",@request_token.secret assert_equal "http://term.ie/oauth/example/authorize.php?oauth_token=requestkey",@request_token.authorize_url @access_token=@request_token.get_access_token assert_not_nil @access_token assert_equal "accesskey",@access_token.token assert_equal "accesssecret",@access_token.secret @response=@access_token.get("/oauth/example/echo_api.php?ok=hello&test=this") assert_not_nil @response assert_equal "200",@response.code assert_equal( "ok=hello&test=this",@response.body) @response=@access_token.post("/oauth/example/echo_api.php",{'ok'=>'hello','test'=>'this'}) assert_not_nil @response assert_equal "200",@response.code assert_equal( "ok=hello&test=this",@response.body) end def test_get_token_sequence_using_fqdn stub_test_ie @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://term.ie", :request_token_url=>"http://term.ie/oauth/example/request_token.php", :access_token_url=>"http://term.ie/oauth/example/access_token.php", :authorize_url=>"http://term.ie/oauth/example/authorize.php" }) assert_equal "http://term.ie/oauth/example/request_token.php",@consumer.request_token_url assert_equal "http://term.ie/oauth/example/access_token.php",@consumer.access_token_url assert @consumer.request_token_url?, "Should use fully qualified request token url" assert @consumer.access_token_url?, "Should use fully qualified access token url" assert @consumer.authorize_url?, "Should use fully qualified url" @request_token=@consumer.get_request_token assert_not_nil @request_token assert_equal "requestkey",@request_token.token assert_equal "requestsecret",@request_token.secret assert_equal "http://term.ie/oauth/example/authorize.php?oauth_token=requestkey",@request_token.authorize_url @access_token=@request_token.get_access_token assert_not_nil @access_token assert_equal "accesskey",@access_token.token assert_equal "accesssecret",@access_token.secret @response=@access_token.get("/oauth/example/echo_api.php?ok=hello&test=this") assert_not_nil @response assert_equal "200",@response.code assert_equal( "ok=hello&test=this",@response.body) @response=@access_token.post("/oauth/example/echo_api.php",{'ok'=>'hello','test'=>'this'}) assert_not_nil @response assert_equal "200",@response.code assert_equal( "ok=hello&test=this",@response.body) end # This test does an actual https request (the result doesn't matter) # to initialize the same way as get_request_token does. Can be any # site that supports https. # # It also generates "warning: using default DH parameters." which I # don't know how to get rid of # def test_serialization_with_https # consumer = OAuth::Consumer.new('token', 'secret', :site => 'https://plazes.net') # consumer.http.verify_mode = OpenSSL::SSL::VERIFY_NONE # consumer.http.get('/') # # assert_nothing_raised do # # Specifically this should not raise TypeError: no marshal_dump # # is defined for class OpenSSL::SSL::SSLContext # Marshal.dump(consumer) # end # end # def test_get_request_token_with_custom_arguments stub_test_ie @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://term.ie", :request_token_path=>"/oauth/example/request_token.php", :access_token_path=>"/oauth/example/access_token.php", :authorize_path=>"/oauth/example/authorize.php" }) @consumer.get_request_token({}, {:scope => "http://www.google.com/calendar/feeds http://picasaweb.google.com/data"}) # Because this is a POST request, create_http_request should take the first element of *arguments # and turn it into URL-encoded data in the body of the POST. end def test_post_with_body_stream stub_test_ie @consumer=OAuth::Consumer.new( "key", "secret", { :site=>"http://term.ie", :request_token_path=>"/oauth/example/request_token.php", :access_token_path=>"/oauth/example/access_token.php", :authorize_path=>"/oauth/example/authorize.php" }) @request_token=@consumer.get_request_token @access_token=@request_token.get_access_token request_body_string = "Hello, hello, hello" request_body_stream = StringIO.new( request_body_string ) @response=@access_token.post("/oauth/example/echo_api.php",request_body_stream) assert_not_nil @response assert_equal "200",@response.code request_body_file = File.open(__FILE__) @response=@access_token.post("/oauth/example/echo_api.php",request_body_file) assert_not_nil @response assert_equal "200",@response.code # unfortunately I don't know of a way to test that the body data was received correctly since the test server at http://term.ie # echos back any non-oauth parameters but not the body. However, this does test that the request is still correctly signed # (including the Content-Length header) and that the server received Content-Length bytes of body since it won't process the # request & respond until the full body length is received. end private def request_parameters_to_s @request_parameters.map { |k,v| "#{k}=#{v}" }.join("&") end end end oauth-0.4.7/test/test_signature_base.rb0000644000004100000410000000151312055513522020230 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'oauth/signature/base' require 'net/http' class SignatureBaseTest < Test::Unit::TestCase def test_that_initialize_requires_one_request_argument assert_raises ArgumentError do OAuth::Signature::Base.new() end end def test_that_initialize_requires_a_valid_request_argument request = nil assert_raises TypeError do OAuth::Signature::Base.new(request) { |token| # just a stub } end end def test_that_initialize_succeeds_when_the_request_proxy_is_valid # this isn't quite valid, but it will do. raw_request = Net::HTTP::Get.new('/test') request = OAuth::RequestProxy.proxy(raw_request) assert_nothing_raised do OAuth::Signature::Base.new(request) { |token| # just a stub } end end end oauth-0.4.7/test/test_em_http_request_proxy.rb0000644000004100000410000001350512055513522021712 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) begin require 'em-http' require 'oauth/request_proxy/em_http_request' class EmHttpRequestProxyTest < Test::Unit::TestCase def test_request_proxy_works_with_simple_request proxy = create_request_proxy assert_equal({}, proxy.parameters) end def test_request_proxy_works_with_query_string_params assert_equal({"name" => ["Fred"]}, create_request_proxy(:query => "name=Fred").parameters) assert_equal({"name" => ["Fred"]}, create_request_proxy(:query => {:name => "Fred"}).parameters) proxy = create_request_proxy(:query => {:name => "Fred"}, :uri => "http://example.com/?awesome=true") assert_equal({"name" => ["Fred"], "awesome" => ["true"]}, proxy.parameters) end def test_request_proxy_works_with_post_body_params_with_correct_content_type proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "POST" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "POST", :body => "a=1" assert_equal({"a" => ["1"]}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "POST", :body => {"a" => 1} assert_equal({"a" => ["1"]}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "PUT" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "PUT", :body => "a=1" assert_equal({"a" => ["1"]}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "PUT", :body => {"a" => 1} assert_equal({"a" => ["1"]}, proxy.parameters) end def test_request_proxy_ignore_post_body_with_invalid_content_type proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "POST" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "POST", :body => "a=1" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "POST", :body => {"a" => 1} assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "PUT" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "PUT", :body => "a=1" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "PUT", :body => {"a" => 1} assert_equal({}, proxy.parameters) end def test_request_proxy_ignores_post_body_with_invalid_method proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "DELETE" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "DELETE", :body => "a=1" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "DELETE", :body => {"a" => 1} assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "GET" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "GET", :body => "a=1" assert_equal({}, proxy.parameters) proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "GET", :body => {"a" => 1} assert_equal({}, proxy.parameters) end def test_request_proxy_works_with_argument_params assert_equal({"a" => ["1"]}, create_request_proxy(:proxy_options => {:parameters => {"a" => "1"}}).parameters) end def test_request_proxy_works_with_mixed_params proxy = create_request_proxy(:proxy_options => {:parameters => {"a" => "1"}},:query => {"c" => "1"}, :uri => "http://example.com/test?b=1") assert_equal({"a" => ["1"], "b" => ["1"], "c" => ["1"]}, proxy.parameters) proxy = create_request_proxy(:proxy_options => {:parameters => {"a" => "1"}}, :body => {"b" => "1"}, :query => {"c" => "1"}, :uri => "http://example.com/test?d=1", :method => "POST", :head => {"Content-Type" => "application/x-www-form-urlencoded"}) assert_equal({"a" => ["1"], "b" => ["1"], "c" => ["1"], "d" => ["1"]}, proxy.parameters) end def test_request_has_the_correct_uri assert_equal "http://example.com/", create_request_proxy.uri assert_equal "http://example.com/?a=1", create_request_proxy(:query => "a=1").uri assert_equal "http://example.com/?a=1", create_request_proxy(:query => {"a" => "1"}).uri end def test_request_proxy_has_correct_method assert_equal "GET", create_request_proxy(:method => "GET").method assert_equal "PUT", create_request_proxy(:method => "PUT").method assert_equal "POST", create_request_proxy(:method => "POST").method assert_equal "DELETE", create_request_proxy(:method => "DELETE").method end protected def create_client(options = {}) method = options.delete(:method) || "GET" uri = options.delete(:uri) || "http://example.com/" client = EventMachine::HttpClient.new("") client.uri = URI.parse(uri) client.method = method.to_s.upcase client.options = options client end def create_request_proxy(opts = {}) arguments = opts.delete(:proxy_options) || {} OAuth::RequestProxy.proxy(create_client(opts), arguments) end end rescue LoadError => e warn "! problem loading em-http, skipping these tests: #{e}" end oauth-0.4.7/test/test_signature.rb0000644000004100000410000000124412055513522017237 0ustar www-datawww-data# -*- encoding: utf-8 -*- require File.expand_path('../test_helper', __FILE__) class TestOauth < Test::Unit::TestCase def test_parameter_escaping_kcode_invariant ruby19 = RUBY_VERSION =~ /^1\.9/ old = $KCODE if !ruby19 begin %w(n N e E s S u U).each do |kcode| $KCODE = kcode if !ruby19 assert_equal '%E3%81%82', OAuth::Helper.escape('あ'), "Failed to correctly escape Japanese under $KCODE = #{kcode}" assert_equal '%C3%A9', OAuth::Helper.escape('é'), "Failed to correctly escape e+acute under $KCODE = #{kcode}" end ensure $KCODE = old if !ruby19 end end end oauth-0.4.7/test/test_net_http_request_proxy.rb0000644000004100000410000000616312055513522022101 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) class NetHTTPRequestProxyTest < Test::Unit::TestCase def test_that_proxy_simple_get_request_works request = Net::HTTP::Get.new('/test?key=value') request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'GET', request_proxy.method end def test_that_proxy_simple_post_request_works_with_arguments request = Net::HTTP::Post.new('/test') params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_post_request_works_with_form_data request = Net::HTTP::Post.new('/test') params = {'key' => 'value'} request.set_form_data(params) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_put_request_works_with_argugments request = Net::HTTP::Put.new('/test') params = {'key' => 'value'} request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'PUT', request_proxy.method end def test_that_proxy_simple_put_request_works_with_form_data request = Net::HTTP::Put.new('/test') params = {'key' => 'value'} request.set_form_data(params) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'}) expected_parameters = {'key' => ['value']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'PUT', request_proxy.method end def test_that_proxy_post_request_uses_post_parameters request = Net::HTTP::Post.new('/test?key=value') request.set_form_data({'key2' => 'value2'}) request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}}) expected_parameters = {'key' => ['value'], 'key2' => ['value2'], 'key3' => ['value3']} assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'http://example.com/test', request_proxy.normalized_uri assert_equal 'POST', request_proxy.method end end oauth-0.4.7/test/test_em_http_client.rb0000644000004100000410000000720112055513522020233 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) begin require 'oauth/client/em_http' class EmHttpClientTest < Test::Unit::TestCase def setup @consumer = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237') @token = OAuth::Token.new('token_411a7f', '3196ffd991c8ebdb') @request_uri = URI.parse('http://example.com/test?key=value') @request_parameters = { 'key' => 'value' } @nonce = 225579211881198842005988698334675835446 @timestamp = "1199645624" # This is really unneeded I guess. @http = Net::HTTP.new(@request_uri.host, @request_uri.port) end def test_that_using_auth_headers_on_get_requests_works request = create_client request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'GET', request.method assert_equal '/test', request.normalize_uri.path assert_equal "key=value", request.normalize_uri.query assert_equal_authz_headers "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"", authz_header(request) end def test_that_using_auth_headers_on_get_requests_works_with_plaintext require 'oauth/signature/plaintext' c = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237',{ :signature_method => 'PLAINTEXT' }) request = create_client request.oauth!(@http, c, @token, {:nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'}) assert_equal 'GET', request.method assert_equal '/test', request.normalize_uri.path assert_equal "key=value", request.normalize_uri.query assert_equal_authz_headers "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"PLAINTEXT\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"", authz_header(request) end def test_that_using_auth_headers_on_post_requests_works request = create_client(:uri => "http://example.com/test", :method => "POST", :body => @request_parameters, :head => {"Content-Type" => "application/x-www-form-urlencoded"}) request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp}) assert_equal 'POST', request.method assert_equal '/test', request.uri.path assert_equal 'key=value', request.normalize_body assert_equal_authz_headers "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"", authz_header(request) end protected def create_client(options = {}) method = options.delete(:method) || "GET" uri = options.delete(:uri) || @request_uri.to_s client = EventMachine::HttpClient.new("") client.uri = URI.parse(uri) client.method = method.to_s.upcase client.options = options client end def authz_header(request) headers = request.options[:head] || {} headers['Authorization'].to_s end def assert_equal_authz_headers(expected, actual) assert !actual.nil? assert_equal expected[0,6], actual[0, 6] assert_equal expected[6..1].split(', ').sort, actual[6..1].split(', ').sort end end rescue LoadError => e warn "! problem loading em-http, skipping these tests: #{e}" end oauth-0.4.7/test/test_token.rb0000644000004100000410000000046712055513522016364 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'oauth/token' class TestToken < Test::Unit::TestCase def setup end def test_token_constructor_produces_valid_token token = OAuth::Token.new('xyz', '123') assert_equal 'xyz', token.token assert_equal '123', token.secret end end oauth-0.4.7/test/test_request_token.rb0000644000004100000410000000327512055513522020134 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) class StubbedToken < OAuth::RequestToken define_method :build_authorize_url_promoted do |root_domain, params| build_authorize_url root_domain, params end end class TestRequestToken < Test::Unit::TestCase def setup # setup a fake req. token. mocking Consumer would be more appropriate... @request_token = OAuth::RequestToken.new( OAuth::Consumer.new("key", "secret", {}), "key", "secret" ) end def test_request_token_builds_authorize_url_connectly_with_additional_params auth_url = @request_token.authorize_url({:oauth_callback => "github.com"}) assert_not_nil auth_url assert_match(/oauth_token/, auth_url) assert_match(/oauth_callback/, auth_url) end def test_request_token_builds_authorize_url_connectly_with_no_or_nil_params # we should only have 1 key in the url returned if we didn't pass anything. # this is the only required param to authenticate the client. auth_url = @request_token.authorize_url(nil) assert_not_nil auth_url assert_match(/\?oauth_token=/, auth_url) auth_url = @request_token.authorize_url assert_not_nil auth_url assert_match(/\?oauth_token=/, auth_url) end #TODO: mock out the Consumer to test the Consumer/AccessToken interaction. def test_get_access_token end def test_build_authorize_url @stubbed_token = StubbedToken.new(nil, nil, nil) assert_respond_to @stubbed_token, :build_authorize_url_promoted url = @stubbed_token.build_authorize_url_promoted( "http://github.com/oauth/authorize", {:foo => "bar bar"}) assert url assert_equal "http://github.com/oauth/authorize?foo=bar+bar", url end end oauth-0.4.7/test/test_rsa_sha1.rb0000644000004100000410000000736612055513522016752 0ustar www-datawww-datarequire File.expand_path('../test_helper', __FILE__) require 'oauth/consumer' require 'oauth/signature/rsa/sha1' class TestSignatureRsaSha1 < Test::Unit::TestCase def setup @request = Net::HTTP::Get.new('/photos?file=vacaction.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_timestamp=1196666512&oauth_nonce=13917289812797014437&oauth_signature_method=RSA-SHA1') @consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03', OpenSSL::PKey::RSA.new(IO.read(File.dirname(__FILE__) + "/keys/rsa.pem"))) end def test_that_rsa_sha1_implements_rsa_sha1 assert OAuth::Signature.available_methods.include?('rsa-sha1') end def test_that_get_request_from_oauth_test_cases_produces_matching_signature_base_string sbs = OAuth::Signature.signature_base_string(@request, { :consumer => @consumer, :uri => 'http://photos.example.net/photos' } ) assert_equal 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacaction.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D13917289812797014437%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1196666512%26oauth_version%3D1.0%26size%3Doriginal', sbs end def test_that_get_request_from_oauth_test_cases_produces_matching_signature signature = OAuth::Signature.sign(@request, { :consumer => @consumer, :uri => 'http://photos.example.net/photos' } ) assert_equal 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=', signature end def test_that_get_request_from_oauth_test_cases_produces_matching_signature_using_private_key_file @consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03',nil) signature = OAuth::Signature.sign(@request, { :consumer => @consumer, :private_key_file=>File.dirname(__FILE__) + "/keys/rsa.pem", :uri => 'http://photos.example.net/photos' } ) assert_equal 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=', signature end def test_that_get_request_from_oauth_test_cases_verifies_signature @request = Net::HTTP::Get.new('/photos?oauth_signature_method=RSA-SHA1&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_timestamp=1196666512&oauth_nonce=13917289812797014437&file=vacaction.jpg&size=original&oauth_signature=jvTp%2FwX1TYtByB1m%2BPbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2%2F9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW%2F%2Fe%2BRinhejgCuzoH26dyF8iY2ZZ%2F5D1ilgeijhV%2FvBka5twt399mXwaYdCwFYE%3D') @consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03',OpenSSL::X509::Certificate.new(IO.read(File.dirname(__FILE__) + "/keys/rsa.cert"))) assert OAuth::Signature.verify(@request, { :consumer => @consumer, :uri => 'http://photos.example.net/photos' } ) end def test_that_get_request_from_oauth_test_cases_verifies_signature_with_pem @request = Net::HTTP::Get.new('/photos?oauth_signature_method=RSA-SHA1&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_timestamp=1196666512&oauth_nonce=13917289812797014437&file=vacaction.jpg&size=original&oauth_signature=jvTp%2FwX1TYtByB1m%2BPbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2%2F9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW%2F%2Fe%2BRinhejgCuzoH26dyF8iY2ZZ%2F5D1ilgeijhV%2FvBka5twt399mXwaYdCwFYE%3D') assert OAuth::Signature.verify(@request, { :consumer => @consumer, :uri => 'http://photos.example.net/photos' } ) end end oauth-0.4.7/test/test_action_controller_request_proxy.rb0000644000004100000410000001123712055513522023772 0ustar www-datawww-datagem 'actionpack', '~> 2.3.8' require File.expand_path('../test_helper', __FILE__) require 'oauth/request_proxy/action_controller_request' require 'action_controller/test_process' class ActionControllerRequestProxyTest < Test::Unit::TestCase def request_proxy(request_method = :get, uri_params = {}, body_params = {}) request = ActionController::TestRequest.new request.set_REQUEST_URI('/') case request_method when :post request.env['REQUEST_METHOD'] = 'POST' when :put request.env['REQUEST_METHOD'] = 'PUT' end request.env['REQUEST_URI'] = '/' request.env['RAW_POST_DATA'] = body_params.to_query request.env['QUERY_STRING'] = body_params.to_query request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' yield request if block_given? OAuth::RequestProxy::ActionControllerRequest.new(request, :parameters => uri_params) end def test_that_proxy_simple_get_request_works_with_query_params request_proxy = request_proxy(:get, {'key'=>'value'}) expected_parameters = [["key", "value"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'GET', request_proxy.method end def test_that_proxy_simple_post_request_works_with_query_params request_proxy = request_proxy(:post, {'key'=>'value'}) expected_parameters = [["key", "value"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_put_request_works_with_query_params request_proxy = request_proxy(:put, {'key'=>'value'}) expected_parameters = [["key", "value"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'PUT', request_proxy.method end def test_that_proxy_simple_get_request_works_with_post_params request_proxy = request_proxy(:get, {}, {'key'=>'value'}) expected_parameters = [] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'GET', request_proxy.method end def test_that_proxy_simple_post_request_works_with_post_params request_proxy = request_proxy(:post, {}, {'key'=>'value'}) expected_parameters = [["key", "value"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_put_request_works_with_post_params request_proxy = request_proxy(:put, {}, {'key'=>'value'}) expected_parameters = [] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'PUT', request_proxy.method end def test_that_proxy_simple_get_request_works_with_mixed_params request_proxy = request_proxy(:get, {'key'=>'value'}, {'key2'=>'value2'}) expected_parameters = [["key", "value"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'GET', request_proxy.method end def test_that_proxy_simple_post_request_works_with_mixed_params request_proxy = request_proxy(:post, {'key'=>'value'}, {'key2'=>'value2'}) expected_parameters = [["key", "value"],["key2", "value2"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'POST', request_proxy.method end def test_that_proxy_simple_put_request_works_with_mixed_params request_proxy = request_proxy(:put, {'key'=>'value'}, {'key2'=>'value2'}) expected_parameters = [["key", "value"]] assert_equal expected_parameters, request_proxy.parameters_for_signature assert_equal 'PUT', request_proxy.method end def test_parameter_keys_should_preserve_brackets_from_hash assert_equal( [["message[body]", "This is a test"]], request_proxy(:post, { :message => { :body => 'This is a test' }}).parameters_for_signature ) end def test_parameter_values_with_amps_should_not_break_parameter_parsing assert_equal( [['message[body]', 'http://foo.com/?a=b&c=d']], request_proxy(:post, { :message => { :body => 'http://foo.com/?a=b&c=d'}}).parameters_for_signature ) end def test_parameter_keys_should_preserve_brackets_from_array assert_equal( [["foo[]", "123"], ["foo[]", "456"]], request_proxy(:post, { :foo => [123, 456] }).parameters_for_signature.sort ) end # TODO disabled; ActionController::TestRequest does not appear to parse # QUERY_STRING def x_test_query_string_parameter_values_should_be_cgi_unescaped request = request_proxy do |r| r.env['QUERY_STRING'] = 'url=http%3A%2F%2Ffoo.com%2F%3Fa%3Db%26c%3Dd' end assert_equal( [['url', 'http://foo.com/?a=b&c=d']], request.parameters_for_signature.sort ) end end oauth-0.4.7/tasks/0000755000004100000410000000000012055513522014017 5ustar www-datawww-dataoauth-0.4.7/tasks/deployment.rake0000644000004100000410000000217612055513522017051 0ustar www-datawww-datadesc 'Release the website and new gem version' task :deploy => [:check_version, :website, :release] do puts "Remember to create SVN tag:" puts "svn copy svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/trunk " + "svn+ssh://#{rubyforge_username}@rubyforge.org/var/svn/#{PATH}/tags/REL-#{VERS} " puts "Suggested comment:" puts "Tagging release #{CHANGES}" end desc 'Runs tasks website_generate and install_gem as a local deployment of the gem' task :local_deploy => [:website_generate, :install_gem] task :check_version do unless ENV['VERSION'] puts 'Must pass a VERSION=x.y.z release version' exit end unless ENV['VERSION'] == VERS puts "Please update your version.rb to match the release version, currently #{VERS}" exit end end desc 'Install the package as a gem, without generating documentation(ri/rdoc)' task :install_gem_no_doc => [:clean, :package] do sh "#{'sudo ' unless Hoe::WINDOZE }gem install pkg/*.gem --no-rdoc --no-ri" end namespace :manifest do desc 'Recreate Manifest.txt to include ALL files' task :refresh do `rake check_manifest | patch -p0 > Manifest.txt` end end oauth-0.4.7/tasks/environment.rake0000644000004100000410000000017312055513522017230 0ustar www-datawww-datatask :ruby_env do RUBY_APP = if RUBY_PLATFORM =~ /java/ "jruby" else "ruby" end unless defined? RUBY_APP end oauth-0.4.7/tasks/website.rake0000644000004100000410000000111112055513522016317 0ustar www-datawww-datadesc 'Generate website files' task :website_generate => :ruby_env do (Dir['website/**/*.txt'] - Dir['website/version*.txt']).each do |txt| sh %{ #{RUBY_APP} script/txt2html #{txt} > #{txt.gsub(/txt$/,'html')} } end end desc 'Upload website files to rubyforge' task :website_upload do host = "#{rubyforge_username}@rubyforge.org" remote_dir = "/var/www/gforge-projects/#{PATH}/" local_dir = 'website' sh %{rsync -aCv #{local_dir}/ #{host}:#{remote_dir}} end desc 'Generate and upload website files' task :website => [:website_generate, :website_upload, :publish_docs] oauth-0.4.7/examples/0000755000004100000410000000000012055513522014510 5ustar www-datawww-dataoauth-0.4.7/examples/yql.rb0000755000004100000410000000222012055513522015641 0ustar www-datawww-data#!/usr/bin/env ruby -rubygems # Sample queries: # ./yql.rb --consumer-key --consumer-secret "show tables" # ./yql.rb --consumer-key --consumer-secret "select * from flickr.photos.search where text='Cat' limit 10" require 'oauth' require 'optparse' require 'json' require 'pp' options = {} option_parser = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options] " opts.on("--consumer-key KEY", "Specifies the consumer key to use.") do |v| options[:consumer_key] = v end opts.on("--consumer-secret SECRET", "Specifies the consumer secret to use.") do |v| options[:consumer_secret] = v end end option_parser.parse! query = ARGV.pop query = STDIN.read if query == "-" if options[:consumer_key].nil? || options[:consumer_secret].nil? || query.nil? puts option_parser.help exit 1 end consumer = OAuth::Consumer.new \ options[:consumer_key], options[:consumer_secret], :site => "http://query.yahooapis.com" access_token = OAuth::AccessToken.new(consumer) response = access_token.request(:get, "/v1/yql?q=#{OAuth::Helper.escape(query)}&format=json") rsp = JSON.parse(response.body) pp rsp oauth-0.4.7/LICENSE0000644000004100000410000000207612055513522013704 0ustar www-datawww-dataCopyright (c) 2007 Blaine Cook, Larry Halff, Pelle Braendgaard Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.oauth-0.4.7/oauth.gemspec0000644000004100000410000001233012055513522015356 0ustar www-datawww-data# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "oauth" s.version = "0.4.7" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Pelle Braendgaard", "Blaine Cook", "Larry Halff", "Jesse Clark", "Jon Crosby", "Seth Fitzsimmons", "Matt Sanford", "Aaron Quint"] s.date = "2012-09-04" s.description = "OAuth Core Ruby implementation" s.email = "oauth-ruby@googlegroups.com" s.executables = ["oauth"] s.extra_rdoc_files = [ "LICENSE", "README.rdoc", "TODO" ] s.files = [ ".gemtest", "Gemfile", "Gemfile.lock", "HISTORY", "LICENSE", "README.rdoc", "Rakefile", "TODO", "bin/oauth", "examples/yql.rb", "lib/digest/hmac.rb", "lib/oauth.rb", "lib/oauth/cli.rb", "lib/oauth/client.rb", "lib/oauth/client/action_controller_request.rb", "lib/oauth/client/em_http.rb", "lib/oauth/client/helper.rb", "lib/oauth/client/net_http.rb", "lib/oauth/consumer.rb", "lib/oauth/core_ext.rb", "lib/oauth/errors.rb", "lib/oauth/errors/error.rb", "lib/oauth/errors/problem.rb", "lib/oauth/errors/unauthorized.rb", "lib/oauth/helper.rb", "lib/oauth/oauth.rb", "lib/oauth/oauth_test_helper.rb", "lib/oauth/request_proxy.rb", "lib/oauth/request_proxy/action_controller_request.rb", "lib/oauth/request_proxy/base.rb", "lib/oauth/request_proxy/curb_request.rb", "lib/oauth/request_proxy/em_http_request.rb", "lib/oauth/request_proxy/jabber_request.rb", "lib/oauth/request_proxy/mock_request.rb", "lib/oauth/request_proxy/net_http.rb", "lib/oauth/request_proxy/rack_request.rb", "lib/oauth/request_proxy/typhoeus_request.rb", "lib/oauth/server.rb", "lib/oauth/signature.rb", "lib/oauth/signature/base.rb", "lib/oauth/signature/hmac/base.rb", "lib/oauth/signature/hmac/md5.rb", "lib/oauth/signature/hmac/rmd160.rb", "lib/oauth/signature/hmac/sha1.rb", "lib/oauth/signature/hmac/sha2.rb", "lib/oauth/signature/md5.rb", "lib/oauth/signature/plaintext.rb", "lib/oauth/signature/rsa/sha1.rb", "lib/oauth/signature/sha1.rb", "lib/oauth/token.rb", "lib/oauth/tokens/access_token.rb", "lib/oauth/tokens/consumer_token.rb", "lib/oauth/tokens/request_token.rb", "lib/oauth/tokens/server_token.rb", "lib/oauth/tokens/token.rb", "oauth.gemspec", "tasks/deployment.rake", "tasks/environment.rake", "tasks/website.rake", "test/cases/oauth_case.rb", "test/cases/spec/1_0-final/test_construct_request_url.rb", "test/cases/spec/1_0-final/test_normalize_request_parameters.rb", "test/cases/spec/1_0-final/test_parameter_encodings.rb", "test/cases/spec/1_0-final/test_signature_base_strings.rb", "test/integration/consumer_test.rb", "test/keys/rsa.cert", "test/keys/rsa.pem", "test/test_access_token.rb", "test/test_action_controller_request_proxy.rb", "test/test_consumer.rb", "test/test_curb_request_proxy.rb", "test/test_em_http_client.rb", "test/test_em_http_request_proxy.rb", "test/test_helper.rb", "test/test_hmac_sha1.rb", "test/test_net_http_client.rb", "test/test_net_http_request_proxy.rb", "test/test_oauth_helper.rb", "test/test_rack_request_proxy.rb", "test/test_request_token.rb", "test/test_rsa_sha1.rb", "test/test_server.rb", "test/test_signature.rb", "test/test_signature_base.rb", "test/test_signature_plain_text.rb", "test/test_token.rb", "test/test_typhoeus_request_proxy.rb" ] s.require_paths = ["lib"] s.rubyforge_project = "oauth" s.rubygems_version = "1.8.23" s.summary = "OAuth Core Ruby implementation" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q, [">= 0"]) s.add_development_dependency(%q, [">= 0"]) s.add_development_dependency(%q, [">= 2.3.5"]) s.add_development_dependency(%q, [">= 1.0.0"]) s.add_development_dependency(%q, [">= 0.9.8"]) s.add_development_dependency(%q, [">= 0.1.13"]) s.add_development_dependency(%q, [">= 0.2.10"]) s.add_development_dependency(%q, [">= 0.6.6.0"]) else s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 2.3.5"]) s.add_dependency(%q, [">= 1.0.0"]) s.add_dependency(%q, [">= 0.9.8"]) s.add_dependency(%q, [">= 0.1.13"]) s.add_dependency(%q, [">= 0.2.10"]) s.add_dependency(%q, [">= 0.6.6.0"]) end else s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 2.3.5"]) s.add_dependency(%q, [">= 1.0.0"]) s.add_dependency(%q, [">= 0.9.8"]) s.add_dependency(%q, [">= 0.1.13"]) s.add_dependency(%q, [">= 0.2.10"]) s.add_dependency(%q, [">= 0.6.6.0"]) end end oauth-0.4.7/HISTORY0000644000004100000410000001522512055513522013763 0ustar www-datawww-data=== 0.4.7 2012-09-03 * Fix merging paths if the path is not empty * Set a configurable timeout for all requests (Rick Olson) * Fix nested hash params in Consumer#request (Ernie Miller) === 0.4.6 2012-04-21 * Fixed nested attributes in #normalize (Shaliko Usubov) * Make use the path component of the :site parameter (Jonathon M. Abbott) * Fixed post body's being dropped in 1.9 (Steven Hammond) * Fixed PUT request handling (Anton Panasenko) === 0.4.5 2011-06-25 * Add explicit require for rsa/sha1 (Juris Galang) * Use webmock to mock all http-requests in tests (Adrian Feldman) * Add gemtest support (Adrian Feldman) * Fix POST Requests with Typhoeus proxy (niedhui) * Mention Typhoeus require in the README (Kim Ahlström) * Fix incorrect hardcoded port (Ian Taylor) * Use Net::HTTPGenericRequest (Jakub Kuźma) === 0.4.4 2010-10-31 * Fix LoadError rescue in tests: return can't be used in this context (Hans de Graaff) * HTTP headers should be strings. (seancribbs) * ensure consumer uri gets set back to original config even if an error occurs (Brian Finney) * Yahoo uses & to split records in OAuth headers (Brian Finney) * Added support for Rails 3 in client/action_controller_request (Pelle) == 0.4.3 2010-09-01 * Fix for em-http proxy (ichverstehe) == 0.4.2 2010-08-13 * Fixed compatibility with Ruby 1.9.2 (ecavazos) * Fixed the em-http request proxy (Joshua Hull) * Fix for oauth proxy string manipulation (Jakub Suder) * Added Bundler (rc) Gemfile for easier dev/testing == 0.4.1 2010-06-16 * Added support for using OAuth with proxies (Marsh Gardiner) * Rails 3 Compatibility fixes (Pelle Braendgaard) * Fixed load errors on tests for missing (non-required) libraries == 0.4.0 2010-04-22 * Added computation of oauth_body_hash as per OAuth Request Body Hash 1.0 Draft 4 (Michael Reinsch) * Added the optional `oauth_session_handle` parameter for the Yahoo implementation (Will Bailey) * Better marshalling implementation (Yoan Blanc) * Added optional block to OAuth::Consumer.get_*_token (Neill Pearman) * Exclude `oauth_callback` with :exclude_callback (Neill Pearman) * Strip extraneous spaces and line breaks from access_token responses (observed in the wild with Yahoo!'s OAuth+OpenID hybrid) (Eric Hartmann) * Stop double-escaping PLAINTEXT signatures (Jimmy Zimmerman) * OAuth::Client::Helper won't override the specified `oauth_version` (Philip Kromer) * Support for Ruby 1.9 (Aaron Quint, Corey Donahoe, et al) * Fixed an encoding / multibyte issue (成田 一生) * Replaced hoe with Jeweler (Aaron Quint) * Support for Typhoeus (Bill Kocik) * Support for em-http (EventMachine) (Darcy Laycock) * Support for curb (André Luis Leal Cardoso Junior) * New website (Aaron Quint) == 0.3.6 2009-09-14 * Added -B CLI option to use the :body authentication scheme (Seth) * Respect `--method` in `authorize` CLI command (Seth) * Support POST and PUT with raw bodies (Yu-Shan Fung et al) * Test clean-up (Xavier Shay, Hannes Tydén) * Added :ca_file consumer option to allow consumer specific certificate override. (Pelle) == 0.3.5 2009-06-03 * `query` CLI command to access protected resources (Seth) * Added -H, -Q CLI options for specifying the authentication scheme (Seth) * Added -O CLI option for specifying a file containing options (Seth) * Support streamable body contents for large request bodies (Seth Cousins) * Support for OAuth 1.0a (Seth) * Added proxy support to OAuth::Consumer (Marshall Huss) * Added --scope CLI option for Google's 'scope' parameter (Seth) == 0.3.4 2009-05-06 * OAuth::Client::Helper uses OAuth::VERSION (chadisfaction) * Fix OAuth::RequestProxy::ActionControllerRequest's handling of params (Tristan Groléat) == 0.3.3 2009-05-04 * Corrected OAuth XMPP namespace (Seth) * Improved error handling for invalid Authorization headers (Matt Sanford) * Fixed signatures for non-ASCII under $KCODE other than 'u' (Matt Sanford) * Fixed edge cases in ActionControllerRequestProxy where params were being incorrectly signed (Marcos Wright Kuhns) * Support for arguments in OAuth::Consumer#get_access_token (Matt Sanford) * Add gem version to user-agent header (Matt Sanford) * Handle input from aggressive form encoding libraries (Matt Wood) == 0.3.2 2009-03-23 * 2xx statuses should be treated as success (Anders Conbere) * Support applications using the MethodOverride Rack middleware (László Bácsi) * `authorize` command for `oauth` CLI (Seth) * Initial support for Problem Reporting extension (Seth) * Verify SSL certificates if CA certificates are available (Seth) * Fixed ActionController parameter escaping behavior (Thiago Arrais, László Bácsi, Brett Gibson, et al) * Fixed signature calculation when both options and a block were provided to OAuth::Signature::Base#initialize (Seth) * Added help to the 'oauth' CLI (Seth) * Fixed a problem when attempting to normalize MockRequest URIs (Seth) == 0.3.1 2009-1-26 * Fixed a problem with relative and absolute token request paths. (Michael Wood) == 0.3.0 2009-1-25 * Support ActionController::Request from Edge Rails (László Bácsi) * Correctly handle multi-valued parameters (Seth) * Added #normalized_parameters to OAuth::RequestProxy::Base (Pelle) * OAuth::Signature.sign and friends now yield the RequestProxy instead of the token when the passed block's arity is 1. (Seth) * Token requests are made to the configured URL rather than generating a potentially incorrect one. (Kellan Elliott-McCrea) * Command-line app for generating signatures. (Seth) * Improved test-cases and compatibility for encoding issues. (Pelle) == 0.2.7 2008-9-10 The lets fix the last release release * Fixed plain text signatures (Andrew Arrow) * Fixed RSA requests using OAuthTokens. (Philip Lipu Tsai) == 0.2.6 2008-9-9 The lets RSA release * Improved support for Ruby 1.8.7 (Bill Kocik) * Fixed RSA verification to support RSA providers now using Ruby and RSA * Improved RSA testing * Omit token when signing with RSA * Added support for 'private_key_file' option for RSA signatures (Chris Mear) * Fixed several edge cases where params were being incorrectly signed (Scott Hill) * Fixed RSA signing (choonkeat) == 0.2.2 2008-2-22 Lets actually support SSL release * Use HTTPS when required. == 0.2 2008-1-19 All together now release This is a big release, where we have merged the efforts of various parties into one common library. This means there are definitely some API changes you should be aware of. They should be minimal but please have a look at the unit tests. == 0.1.2 2007-12-1 * Fixed checks for missing OAuth params to improve performance * Includes Pat's fix for getting the realm out. == 0.1.1 2007-11-26 * First release as a GEM * Moved all non-Rails functionality from the Rails plugin: http://code.google.com/p/oauth-plugin/ oauth-0.4.7/README.rdoc0000644000004100000410000000516112055513522014503 0ustar www-datawww-data= Ruby OAuth == What This is a RubyGem for implementing both OAuth clients and servers in Ruby applications. See the OAuth specs http://oauth.net/core/1.0/ == Installing sudo gem install oauth The source code is now hosted on the OAuth GitHub Project http://github.com/oauth/oauth-ruby == The basics This is a ruby library which is intended to be used in creating Ruby Consumer and Service Provider applications. It is NOT a Rails plugin, but could easily be used for the foundation for such a Rails plugin. As a matter of fact it has been pulled out from an OAuth Rails Plugin http://code.google.com/p/oauth-plugin/ which now requires this GEM. == Demonstration of usage We need to specify the oauth_callback url explicitly, otherwise it defaults to "oob" (Out of Band) @callback_url = "http://127.0.0.1:3000/oauth/callback" Create a new consumer instance by passing it a configuration hash: @consumer = OAuth::Consumer.new("key","secret", :site => "https://agree2") Start the process by requesting a token @request_token = @consumer.get_request_token(:oauth_callback => @callback_url) session[:request_token] = @request_token redirect_to @request_token.authorize_url(:oauth_callback => @callback_url) When user returns create an access_token @access_token = @request_token.get_access_token @photos = @access_token.get('/photos.xml') Now that you have an access token, you can use Typhoeus to interact with the OAuth provider if you choose. require 'oauth/request_proxy/typhoeus_request' oauth_params = {:consumer => oauth_consumer, :token => access_token} hydra = Typhoeus::Hydra.new 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}) # Signs the request hydra.queue(req) hydra.run @response = req.response == More Information * RDoc: http://rdoc.info/projects/oauth/oauth-ruby/ * Mailing List/Google Group: http://groups.google.com/group/oauth-ruby == How to submit patches The source code is now hosted on the OAuth GitHub Project http://github.com/oauth/oauth-ruby To submit a patch, please fork the oauth project and create a patch with tests. Once you're happy with it send a pull request and post a message to the google group. == License This code is free to use under the terms of the MIT license. == Contact OAuth Ruby has been created and maintained by a large number of talented individuals. The current maintainer is Aaron Quint (quirkey). Comments are welcome. Send an email to via the OAuth Ruby mailing list http://groups.google.com/group/oauth-rubyoauth-0.4.7/Rakefile0000644000004100000410000000241612055513522014342 0ustar www-datawww-data%w[rubygems rake rake/clean rake/testtask fileutils].each { |f| require f } $LOAD_PATH << File.dirname(__FILE__) + '/lib' require 'oauth' begin require 'jeweler' Jeweler::Tasks.new do |s| s.name = %q{oauth} s.version = OAuth::VERSION s.authors = ["Pelle Braendgaard", "Blaine Cook", "Larry Halff", "Jesse Clark", "Jon Crosby", "Seth Fitzsimmons", "Matt Sanford", "Aaron Quint"] s.email = "oauth-ruby@googlegroups.com" s.description = "OAuth Core Ruby implementation" s.summary = s.description s.rubyforge_project = %q{oauth} s.add_development_dependency(%q, [">=2.3.5"]) s.add_development_dependency(%q, [">= 1.0.0"]) s.add_development_dependency(%q, [">= 0.9.8"]) s.add_development_dependency(%q, [">= 0.1.13"]) s.add_development_dependency(%q, [">= 0.2.10"]) s.add_development_dependency(%q, [">= 0.6.6.0"]) s.files.include '.gemtest' end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler" end Rake::TestTask.new do |t| t.libs << "test" t.test_files = FileList['test/**/*test*.rb'] t.verbose = true end Dir['tasks/**/*.rake'].each { |t| load t } task :default => :test oauth-0.4.7/TODO0000644000004100000410000000211612055513522013362 0ustar www-datawww-dataCommon use-cases should be streamlined: * I have a URL that I want to sign (given consumer key/secret, optional token/secret, optional nonce/timestamp). * I have a URL that I want to sign AND I want to see what the components (e.g. signature base string, etc.) are while it's being signed (i.e. verbose signing). * I have a URL that I want to sign and I only want the signature. * I have a URL that I want to sign and I want something suitable to put in {the header, the querystring, XMPP}. * I want to make a query to an OAuth-enabled web service (with sensible errors, if available). * I want to host an OAuth-enabled web service. * I want to test my OAuth-enabled web service (i.e. test helpers) Example applications for: * Ning * Fire Eagle * Google (blogger, contacts) * Twitter * YOS / YQL * Netflix In addition to providing best practices of use, these can also be part of the pre-release checks to make sure that there have been no regressions. Random TODOs: * finish CLI * sensible Exception hierarchy * Tokens as Modules * don't tie to Net::HTTP * Take a look at Curb HTTP Verbsoauth-0.4.7/.gemtest0000644000004100000410000000000012055513522014331 0ustar www-datawww-dataoauth-0.4.7/bin/0000755000004100000410000000000012055513522013442 5ustar www-datawww-dataoauth-0.4.7/bin/oauth0000755000004100000410000000013112055513522014503 0ustar www-datawww-data#!/usr/bin/env ruby require "oauth/cli" OAuth::CLI.execute(STDOUT, STDIN, STDERR, ARGV)oauth-0.4.7/metadata.yml0000644000004100000410000001531012055513522015175 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: oauth version: !ruby/object:Gem::Version version: 0.4.7 prerelease: platform: ruby authors: - Pelle Braendgaard - Blaine Cook - Larry Halff - Jesse Clark - Jon Crosby - Seth Fitzsimmons - Matt Sanford - Aaron Quint autorequire: bindir: bin cert_chain: [] date: 2012-09-04 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: rake requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: jeweler requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: actionpack requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 2.3.5 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 2.3.5 - !ruby/object:Gem::Dependency name: rack requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 1.0.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 1.0.0 - !ruby/object:Gem::Dependency name: mocha requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.9.8 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.9.8 - !ruby/object:Gem::Dependency name: typhoeus requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.1.13 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.1.13 - !ruby/object:Gem::Dependency name: em-http-request requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.2.10 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.2.10 - !ruby/object:Gem::Dependency name: curb requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.6.6.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: 0.6.6.0 description: OAuth Core Ruby implementation email: oauth-ruby@googlegroups.com executables: - oauth extensions: [] extra_rdoc_files: - LICENSE - README.rdoc - TODO files: - .gemtest - Gemfile - Gemfile.lock - HISTORY - LICENSE - README.rdoc - Rakefile - TODO - bin/oauth - examples/yql.rb - lib/digest/hmac.rb - lib/oauth.rb - lib/oauth/cli.rb - lib/oauth/client.rb - lib/oauth/client/action_controller_request.rb - lib/oauth/client/em_http.rb - lib/oauth/client/helper.rb - lib/oauth/client/net_http.rb - lib/oauth/consumer.rb - lib/oauth/core_ext.rb - lib/oauth/errors.rb - lib/oauth/errors/error.rb - lib/oauth/errors/problem.rb - lib/oauth/errors/unauthorized.rb - lib/oauth/helper.rb - lib/oauth/oauth.rb - lib/oauth/oauth_test_helper.rb - lib/oauth/request_proxy.rb - lib/oauth/request_proxy/action_controller_request.rb - lib/oauth/request_proxy/base.rb - lib/oauth/request_proxy/curb_request.rb - lib/oauth/request_proxy/em_http_request.rb - lib/oauth/request_proxy/jabber_request.rb - lib/oauth/request_proxy/mock_request.rb - lib/oauth/request_proxy/net_http.rb - lib/oauth/request_proxy/rack_request.rb - lib/oauth/request_proxy/typhoeus_request.rb - lib/oauth/server.rb - lib/oauth/signature.rb - lib/oauth/signature/base.rb - lib/oauth/signature/hmac/base.rb - lib/oauth/signature/hmac/md5.rb - lib/oauth/signature/hmac/rmd160.rb - lib/oauth/signature/hmac/sha1.rb - lib/oauth/signature/hmac/sha2.rb - lib/oauth/signature/md5.rb - lib/oauth/signature/plaintext.rb - lib/oauth/signature/rsa/sha1.rb - lib/oauth/signature/sha1.rb - lib/oauth/token.rb - lib/oauth/tokens/access_token.rb - lib/oauth/tokens/consumer_token.rb - lib/oauth/tokens/request_token.rb - lib/oauth/tokens/server_token.rb - lib/oauth/tokens/token.rb - oauth.gemspec - tasks/deployment.rake - tasks/environment.rake - tasks/website.rake - test/cases/oauth_case.rb - test/cases/spec/1_0-final/test_construct_request_url.rb - test/cases/spec/1_0-final/test_normalize_request_parameters.rb - test/cases/spec/1_0-final/test_parameter_encodings.rb - test/cases/spec/1_0-final/test_signature_base_strings.rb - test/integration/consumer_test.rb - test/keys/rsa.cert - test/keys/rsa.pem - test/test_access_token.rb - test/test_action_controller_request_proxy.rb - test/test_consumer.rb - test/test_curb_request_proxy.rb - test/test_em_http_client.rb - test/test_em_http_request_proxy.rb - test/test_helper.rb - test/test_hmac_sha1.rb - test/test_net_http_client.rb - test/test_net_http_request_proxy.rb - test/test_oauth_helper.rb - test/test_rack_request_proxy.rb - test/test_request_token.rb - test/test_rsa_sha1.rb - test/test_server.rb - test/test_signature.rb - test/test_signature_base.rb - test/test_signature_plain_text.rb - test/test_token.rb - test/test_typhoeus_request_proxy.rb homepage: licenses: [] post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: oauth rubygems_version: 1.8.23 signing_key: specification_version: 3 summary: OAuth Core Ruby implementation test_files: [] oauth-0.4.7/Gemfile0000644000004100000410000000037712055513522014174 0ustar www-datawww-datasource :rubygems group :development do gem 'rake' gem 'jeweler' end group :test do gem 'actionpack', '~>2.3.8' gem 'mocha', '>=0.9.8' gem 'typhoeus', '>=0.1.13' gem 'em-http-request', "0.2.11" gem 'curb', ">= 0.6.6.0" gem 'webmock' end oauth-0.4.7/lib/0000755000004100000410000000000012055513522013440 5ustar www-datawww-dataoauth-0.4.7/lib/digest/0000755000004100000410000000000012055513522014717 5ustar www-datawww-dataoauth-0.4.7/lib/digest/hmac.rb0000644000004100000410000000413612055513522016160 0ustar www-datawww-data# = digest/hmac.rb # # An implementation of HMAC keyed-hashing algorithm # # == Overview # # This library adds a method named hmac() to Digest classes, which # creates a Digest class for calculating HMAC digests. # # == Examples # # require 'digest/hmac' # # # one-liner example # puts Digest::HMAC.hexdigest("data", "hash key", Digest::SHA1) # # # rather longer one # hmac = Digest::HMAC.new("foo", Digest::RMD160) # # buf = "" # while stream.read(16384, buf) # hmac.update(buf) # end # # puts hmac.bubblebabble # # == License # # Copyright (c) 2006 Akinori MUSHA # # Documentation by Akinori MUSHA # # All rights reserved. You can redistribute and/or modify it under # the same terms as Ruby. # # $Id: hmac.rb 14881 2008-01-04 07:26:14Z akr $ # require 'digest' unless defined?(Digest::HMAC) module Digest class HMAC < Digest::Class def initialize(key, digester) @md = digester.new block_len = @md.block_length if key.bytesize > block_len key = @md.digest(key) end ipad = Array.new(block_len).fill(0x36) opad = Array.new(block_len).fill(0x5c) key.bytes.each_with_index { |c, i| ipad[i] ^= c opad[i] ^= c } @key = key.freeze @ipad = ipad.inject('') { |s, c| s << c.chr }.freeze @opad = opad.inject('') { |s, c| s << c.chr }.freeze @md.update(@ipad) end def initialize_copy(other) @md = other.instance_eval { @md.clone } end def update(text) @md.update(text) self end alias << update def reset @md.reset @md.update(@ipad) self end def finish d = @md.digest! @md.update(@opad) @md.update(d) @md.digest! end private :finish def digest_length @md.digest_length end def block_length @md.block_length end def inspect sprintf('#<%s: key=%s, digest=%s>', self.class.name, @key.inspect, @md.inspect.sub(/^\#<(.*)>$/) { $1 }); end end end end oauth-0.4.7/lib/oauth/0000755000004100000410000000000012055513522014560 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/client.rb0000644000004100000410000000004712055513522016364 0ustar www-datawww-datamodule OAuth module Client end end oauth-0.4.7/lib/oauth/cli.rb0000644000004100000410000003054712055513522015665 0ustar www-datawww-datarequire 'optparse' require 'oauth' module OAuth class CLI SUPPORTED_COMMANDS = { "authorize" => "Obtain an access token and secret for a user", "debug" => "Verbosely generate an OAuth signature", "query" => "Query a protected resource", "sign" => "Generate an OAuth signature", "version" => "Display the current version of the library" } attr_reader :command attr_reader :options attr_reader :stdout, :stdin def self.execute(stdout, stdin, stderr, arguments = []) self.new.execute(stdout, stdin, stderr, arguments) end def initialize @options = {} # don't dump a backtrace on a ^C trap(:INT) { exit } end def execute(stdout, stdin, stderr, arguments = []) @stdout = stdout @stdin = stdin @stderr = stderr extract_command_and_parse_options(arguments) if sufficient_options? && valid_command? if command == "debug" @command = "sign" @options[:verbose] = true end case command # TODO move command logic elsewhere when "authorize" begin consumer = OAuth::Consumer.new \ options[:oauth_consumer_key], options[:oauth_consumer_secret], :access_token_url => options[:access_token_url], :authorize_url => options[:authorize_url], :request_token_url => options[:request_token_url], :scheme => options[:scheme], :http_method => options[:method].to_s.downcase.to_sym # parameters for OAuth 1.0a oauth_verifier = nil # get a request token request_token = consumer.get_request_token({ :oauth_callback => options[:oauth_callback] }, { "scope" => options[:scope] }) if request_token.callback_confirmed? stdout.puts "Server appears to support OAuth 1.0a; enabling support." options[:version] = "1.0a" end stdout.puts "Please visit this url to authorize:" stdout.puts request_token.authorize_url if options[:version] == "1.0a" stdout.puts "Please enter the verification code provided by the SP (oauth_verifier):" oauth_verifier = stdin.gets.chomp else stdout.puts "Press return to continue..." stdin.gets end begin # get an access token access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier) stdout.puts "Response:" access_token.params.each do |k,v| stdout.puts " #{k}: #{v}" unless k.is_a?(Symbol) end rescue OAuth::Unauthorized => e stderr.puts "A problem occurred while attempting to obtain an access token:" stderr.puts e stderr.puts e.request.body end rescue OAuth::Unauthorized => e stderr.puts "A problem occurred while attempting to authorize:" stderr.puts e stderr.puts e.request.body end when "query" consumer = OAuth::Consumer.new \ options[:oauth_consumer_key], options[:oauth_consumer_secret], :scheme => options[:scheme] access_token = OAuth::AccessToken.new(consumer, options[:oauth_token], options[:oauth_token_secret]) # append params to the URL uri = URI.parse(options[:uri]) params = prepare_parameters.map { |k,v| v.map { |v2| "#{URI.encode(k)}=#{URI.encode(v2)}" } * "&" } uri.query = [uri.query, *params].reject { |x| x.nil? } * "&" p uri.to_s response = access_token.request(options[:method].downcase.to_sym, uri.to_s) puts "#{response.code} #{response.message}" puts response.body when "sign" parameters = prepare_parameters request = OAuth::RequestProxy.proxy \ "method" => options[:method], "uri" => options[:uri], "parameters" => parameters if verbose? stdout.puts "OAuth parameters:" request.oauth_parameters.each do |k,v| stdout.puts " " + [k, v] * ": " end stdout.puts if request.non_oauth_parameters.any? stdout.puts "Parameters:" request.non_oauth_parameters.each do |k,v| stdout.puts " " + [k, v] * ": " end stdout.puts end end request.sign! \ :consumer_secret => options[:oauth_consumer_secret], :token_secret => options[:oauth_token_secret] if verbose? stdout.puts "Method: #{request.method}" stdout.puts "URI: #{request.uri}" stdout.puts "Normalized params: #{request.normalized_parameters}" unless options[:xmpp] stdout.puts "Signature base string: #{request.signature_base_string}" if options[:xmpp] stdout.puts stdout.puts "XMPP Stanza:" stdout.puts <<-EOS #{request.oauth_consumer_key} #{request.oauth_token} #{request.oauth_signature_method} #{request.oauth_signature} #{request.oauth_timestamp} #{request.oauth_nonce} #{request.oauth_version} EOS stdout.puts stdout.puts "Note: You may want to use bare JIDs in your URI." stdout.puts else stdout.puts "OAuth Request URI: #{request.signed_uri}" stdout.puts "Request URI: #{request.signed_uri(false)}" stdout.puts "Authorization header: #{request.oauth_header(:realm => options[:realm])}" end stdout.puts "Signature: #{request.oauth_signature}" stdout.puts "Escaped signature: #{OAuth::Helper.escape(request.oauth_signature)}" else stdout.puts request.oauth_signature end when "version" puts "OAuth for Ruby #{OAuth::VERSION}" end else usage end end protected def extract_command_and_parse_options(arguments) @command = arguments[-1] parse_options(arguments[0..-1]) end def option_parser(arguments = "") # TODO add realm parameter # TODO add user-agent parameter option_parser = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options] " # defaults options[:oauth_nonce] = OAuth::Helper.generate_key options[:oauth_signature_method] = "HMAC-SHA1" options[:oauth_timestamp] = OAuth::Helper.generate_timestamp options[:oauth_version] = "1.0" options[:method] = :post options[:params] = [] options[:scheme] = :header options[:version] = "1.0" ## Common Options opts.on("-B", "--body", "Use the request body for OAuth parameters.") do options[:scheme] = :body end opts.on("--consumer-key KEY", "Specifies the consumer key to use.") do |v| options[:oauth_consumer_key] = v end opts.on("--consumer-secret SECRET", "Specifies the consumer secret to use.") do |v| options[:oauth_consumer_secret] = v end opts.on("-H", "--header", "Use the 'Authorization' header for OAuth parameters (default).") do options[:scheme] = :header end opts.on("-Q", "--query-string", "Use the query string for OAuth parameters.") do options[:scheme] = :query_string end opts.on("-O", "--options FILE", "Read options from a file") do |v| arguments.unshift(*open(v).readlines.map { |l| l.chomp.split(" ") }.flatten) end ## Options for signing and making requests opts.separator("\n options for signing and querying") opts.on("--method METHOD", "Specifies the method (e.g. GET) to use when signing.") do |v| options[:method] = v end opts.on("--nonce NONCE", "Specifies the none to use.") do |v| options[:oauth_nonce] = v end opts.on("--parameters PARAMS", "Specifies the parameters to use when signing.") do |v| options[:params] << v end opts.on("--signature-method METHOD", "Specifies the signature method to use; defaults to HMAC-SHA1.") do |v| options[:oauth_signature_method] = v end opts.on("--secret SECRET", "Specifies the token secret to use.") do |v| options[:oauth_token_secret] = v end opts.on("--timestamp TIMESTAMP", "Specifies the timestamp to use.") do |v| options[:oauth_timestamp] = v end opts.on("--token TOKEN", "Specifies the token to use.") do |v| options[:oauth_token] = v end opts.on("--realm REALM", "Specifies the realm to use.") do |v| options[:realm] = v end opts.on("--uri URI", "Specifies the URI to use when signing.") do |v| options[:uri] = v end opts.on(:OPTIONAL, "--version VERSION", "Specifies the OAuth version to use.") do |v| if v options[:oauth_version] = v else @command = "version" end end opts.on("--no-version", "Omit oauth_version.") do options[:oauth_version] = nil end opts.on("--xmpp", "Generate XMPP stanzas.") do options[:xmpp] = true options[:method] ||= "iq" end opts.on("-v", "--verbose", "Be verbose.") do options[:verbose] = true end ## Options for authorization opts.separator("\n options for authorization") opts.on("--access-token-url URL", "Specifies the access token URL.") do |v| options[:access_token_url] = v end opts.on("--authorize-url URL", "Specifies the authorization URL.") do |v| options[:authorize_url] = v end opts.on("--callback-url URL", "Specifies a callback URL.") do |v| options[:oauth_callback] = v end opts.on("--request-token-url URL", "Specifies the request token URL.") do |v| options[:request_token_url] = v end opts.on("--scope SCOPE", "Specifies the scope (Google-specific).") do |v| options[:scope] = v end end end def parse_options(arguments) option_parser(arguments).parse!(arguments) end def prepare_parameters escaped_pairs = options[:params].collect do |pair| if pair =~ /:/ Hash[*pair.split(":", 2)].collect do |k,v| [CGI.escape(k.strip), CGI.escape(v.strip)] * "=" end else pair end end querystring = escaped_pairs * "&" cli_params = CGI.parse(querystring) { "oauth_consumer_key" => options[:oauth_consumer_key], "oauth_nonce" => options[:oauth_nonce], "oauth_timestamp" => options[:oauth_timestamp], "oauth_token" => options[:oauth_token], "oauth_signature_method" => options[:oauth_signature_method], "oauth_version" => options[:oauth_version] }.reject { |k,v| v.nil? || v == "" }.merge(cli_params) end def sufficient_options? case command # TODO move command logic elsewhere when "authorize" options[:oauth_consumer_key] && options[:oauth_consumer_secret] && options[:access_token_url] && options[:authorize_url] && options[:request_token_url] when "version" true else options[:oauth_consumer_key] && options[:oauth_consumer_secret] && options[:method] && options[:uri] end end def usage stdout.puts option_parser.help stdout.puts stdout.puts "Available commands:" SUPPORTED_COMMANDS.each do |command, desc| puts " #{command.ljust(15)}#{desc}" end end def valid_command? SUPPORTED_COMMANDS.keys.include?(command) end def verbose? options[:verbose] end end end oauth-0.4.7/lib/oauth/token.rb0000644000004100000410000000033312055513522016224 0ustar www-datawww-data# this exists for backwards-compatibility require 'oauth/tokens/token' require 'oauth/tokens/server_token' require 'oauth/tokens/consumer_token' require 'oauth/tokens/request_token' require 'oauth/tokens/access_token' oauth-0.4.7/lib/oauth/request_proxy/0000755000004100000410000000000012055513522017511 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/request_proxy/em_http_request.rb0000644000004100000410000000310412055513522023244 0ustar www-datawww-datarequire '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 oauth-0.4.7/lib/oauth/request_proxy/action_controller_request.rb0000644000004100000410000000316712055513522025335 0ustar www-datawww-datarequire 'active_support' require 'action_controller' require 'action_controller/request' require 'uri' module OAuth::RequestProxy class ActionControllerRequest < OAuth::RequestProxy::Base proxies(defined?(ActionController::AbstractRequest) ? ActionController::AbstractRequest : ActionController::Request) def method request.method.to_s.upcase end def uri request.url end def parameters if options[:clobber_request] options[:parameters] || {} else params = request_params.merge(query_params).merge(header_params) params.stringify_keys! if params.respond_to?(:stringify_keys!) params.merge(options[:parameters] || {}) end end # Override from OAuth::RequestProxy::Base to avoid roundtrip # conversion to Hash or Array and thus preserve the original # parameter names def parameters_for_signature params = [] params << options[:parameters].to_query if options[:parameters] unless options[:clobber_request] params << header_params.to_query 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 params. join('&').split('&'). reject(&:blank?). map { |p| p.split('=').map{|esc| CGI.unescape(esc)} }. reject { |kv| kv[0] == 'oauth_signature'} end protected def query_params request.query_parameters end def request_params request.request_parameters end end end oauth-0.4.7/lib/oauth/request_proxy/net_http.rb0000644000004100000410000000325012055513522021663 0ustar www-datawww-datarequire 'oauth/request_proxy/base' require 'net/http' require 'uri' require 'cgi' module OAuth::RequestProxy::Net module HTTP class HTTPRequest < OAuth::RequestProxy::Base proxies ::Net::HTTPGenericRequest def method request.method end def uri options[:uri].to_s end def parameters if options[:clobber_request] options[:parameters] else all_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) && v request_params[k] << v else request_params[k] = [v] end end end request_params end def query_string params = [ query_params, auth_header_params ] 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 def post_params request.body end def auth_header_params return nil unless request['Authorization'] && request['Authorization'][0,5] == 'OAuth' auth_params = request['Authorization'] end end end end oauth-0.4.7/lib/oauth/request_proxy/base.rb0000644000004100000410000001033012055513522020745 0ustar www-datawww-datarequire 'oauth/request_proxy' require 'oauth/helper' module OAuth::RequestProxy class Base include OAuth::Helper def self.proxies(klass) OAuth::RequestProxy.available_proxies[klass] = self end 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 ## OAuth parameters def oauth_callback parameters['oauth_callback'] end def oauth_consumer_key parameters['oauth_consumer_key'] end def oauth_nonce parameters['oauth_nonce'] end def oauth_signature # TODO can this be nil? [parameters['oauth_signature']].flatten.first || "" end def oauth_signature_method case parameters['oauth_signature_method'] when Array parameters['oauth_signature_method'].first else parameters['oauth_signature_method'] end end def oauth_timestamp parameters['oauth_timestamp'] end def oauth_token parameters['oauth_token'] end def oauth_verifier parameters['oauth_verifier'] end def oauth_version parameters["oauth_version"] end # TODO deprecate these alias_method :consumer_key, :oauth_consumer_key alias_method :token, :oauth_token alias_method :nonce, :oauth_nonce alias_method :timestamp, :oauth_timestamp alias_method :signature, :oauth_signature alias_method :signature_method, :oauth_signature_method ## Parameter accessors def parameters raise NotImplementedError, "Must be implemented by subclasses" end def parameters_for_signature parameters.reject { |k,v| k == "oauth_signature" || unsigned_parameters.include?(k)} end def oauth_parameters parameters.select { |k,v| OAuth::PARAMETERS.include?(k) }.reject { |k,v| v == "" } end def non_oauth_parameters parameters.reject { |k,v| OAuth::PARAMETERS.include?(k) } end # See 9.1.2 in specs def normalized_uri u = URI.parse(uri) "#{u.scheme.downcase}://#{u.host.downcase}#{(u.scheme.downcase == 'http' && u.port != 80) || (u.scheme.downcase == 'https' && u.port != 443) ? ":#{u.port}" : ""}#{(u.path && u.path != '') ? u.path : '/'}" end # See 9.1.1. in specs Normalize Request Parameters def normalized_parameters normalize(parameters_for_signature) end def sign(options = {}) OAuth::Signature.sign(self, options) end def sign!(options = {}) parameters["oauth_signature"] = sign(options) @signed = true signature end # See 9.1 in specs def signature_base_string base = [method, normalized_uri, normalized_parameters] base.map { |v| escape(v) }.join("&") end # Has this request been signed yet? def signed? @signed end # URI, including OAuth parameters def signed_uri(with_oauth = true) if signed? if with_oauth params = parameters else params = non_oauth_parameters end [uri, normalize(params)] * "?" else STDERR.puts "This request has not yet been signed!" end end # Authorization header for OAuth def oauth_header(options = {}) header_params_str = oauth_parameters.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ') realm = "realm=\"#{options[:realm]}\", " if options[:realm] "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 %w( X-HTTP_AUTHORIZATION Authorization HTTP_AUTHORIZATION ).each do |header| next unless request.env.include?(header) header = request.env[header] next unless header[0,6] == 'OAuth ' # parse the header into a Hash oauth_params = OAuth::Helper.parse_header(header) # remove non-OAuth parameters oauth_params.reject! { |k,v| k !~ /^oauth_/ } return oauth_params end return {} end end end oauth-0.4.7/lib/oauth/request_proxy/curb_request.rb0000644000004100000410000000256312055513522022547 0ustar www-datawww-data 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 oauth-0.4.7/lib/oauth/request_proxy/jabber_request.rb0000644000004100000410000000160312055513522023033 0ustar www-datawww-datarequire 'xmpp4r' require 'oauth/request_proxy/base' module OAuth module RequestProxy class JabberRequest < OAuth::RequestProxy::Base proxies Jabber::Iq proxies Jabber::Presence proxies Jabber::Message def parameters return @params if @params @params = {} oauth = @request.get_elements('//oauth').first return @params unless oauth %w( oauth_token oauth_consumer_key oauth_signature_method oauth_signature oauth_timestamp oauth_nonce oauth_version ).each do |param| next unless element = oauth.first_element(param) @params[param] = element.text end @params end def method @request.name end def uri [@request.from.strip.to_s, @request.to.strip.to_s].join("&") end def normalized_uri uri end end end end oauth-0.4.7/lib/oauth/request_proxy/typhoeus_request.rb0000644000004100000410000000245012055513522023467 0ustar www-datawww-datarequire '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 oauth-0.4.7/lib/oauth/request_proxy/rack_request.rb0000644000004100000410000000157212055513522022533 0ustar www-datawww-datarequire 'oauth/request_proxy/base' require 'uri' require 'rack' module OAuth::RequestProxy class RackRequest < OAuth::RequestProxy::Base proxies Rack::Request def method request.env["rack.methodoverride.original_method"] || request.request_method end def uri request.url end def parameters if options[:clobber_request] options[:parameters] || {} else params = request_params.merge(query_params).merge(header_params) params.merge(options[:parameters] || {}) end end def signature parameters['oauth_signature'] end protected def query_params request.GET end def 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 oauth-0.4.7/lib/oauth/request_proxy/mock_request.rb0000644000004100000410000000213312055513522022536 0ustar www-datawww-datarequire 'oauth/request_proxy/base' module OAuth module RequestProxy # RequestProxy for Hashes to facilitate simpler signature creation. # Usage: # request = OAuth::RequestProxy.proxy \ # "method" => "iq", # "uri" => [from, to] * "&", # "parameters" => { # "oauth_consumer_key" => oauth_consumer_key, # "oauth_token" => oauth_token, # "oauth_signature_method" => "HMAC-SHA1" # } # # signature = OAuth::Signature.sign \ # request, # :consumer_secret => oauth_consumer_secret, # :token_secret => oauth_token_secret, class MockRequest < OAuth::RequestProxy::Base proxies Hash def parameters @request["parameters"] end def method @request["method"] end def normalized_uri super rescue # if this is a non-standard URI, it may not parse properly # in that case, assume that it's already been normalized uri end def uri @request["uri"] end end end end oauth-0.4.7/lib/oauth/tokens/0000755000004100000410000000000012055513522016063 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/tokens/server_token.rb0000644000004100000410000000025012055513522021113 0ustar www-datawww-datamodule OAuth # Used on the server for generating tokens class ServerToken < Token def initialize super(generate_key(16), generate_key) end end end oauth-0.4.7/lib/oauth/tokens/token.rb0000644000004100000410000000051312055513522017527 0ustar www-datawww-datamodule OAuth # Superclass for the various tokens used by OAuth class Token include OAuth::Helper attr_accessor :token, :secret def initialize(token, secret) @token = token @secret = secret end def to_query "oauth_token=#{escape(token)}&oauth_secret=#{escape(secret)}" end end end oauth-0.4.7/lib/oauth/tokens/access_token.rb0000644000004100000410000000565712055513522021066 0ustar www-datawww-datamodule OAuth # The Access Token is used for the actual "real" web service calls that you perform against the server 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) request_uri = URI.parse(path) site_uri = consumer.uri is_service_uri_different = (request_uri.absolute? && request_uri != site_uri) 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 @response end # Make a regular GET request using AccessToken # # @response = @token.get('/people') # @response = @token.get('/people', { 'Accept'=>'application/xml' }) # def get(path, headers = {}) request(:get, path, headers) end # Make a regular HEAD request using AccessToken # # @response = @token.head('/people') # def head(path, headers = {}) request(:head, path, headers) end # Make a regular POST request using AccessToken # # @response = @token.post('/people') # @response = @token.post('/people', { :name => 'Bob', :email => 'bob@mailinator.com' }) # @response = @token.post('/people', { :name => 'Bob', :email => 'bob@mailinator.com' }, { 'Accept' => 'application/xml' }) # @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 = {}) request(:post, path, body, headers) end # Make a regular PUT request using AccessToken # # @response = @token.put('/people/123') # @response = @token.put('/people/123', { :name => 'Bob', :email => 'bob@mailinator.com' }) # @response = @token.put('/people/123', { :name => 'Bob', :email => 'bob@mailinator.com' }, { 'Accept' => 'application/xml' }) # @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 = {}) 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 = {}) request(:delete, path, headers) end end end oauth-0.4.7/lib/oauth/tokens/request_token.rb0000644000004100000410000000210212055513522021273 0ustar www-datawww-datamodule OAuth # The RequestToken is used for the initial Request. # This is normally created by the Consumer object. class RequestToken < ConsumerToken # Generate an authorization URL for user authorization def authorize_url(params = nil) params = (params || {}).merge(:oauth_token => self.token) build_authorize_url(consumer.authorize_url, params) end def callback_confirmed? params[:oauth_callback_confirmed] == "true" end # exchange for AccessToken on server def get_access_token(options = {}, *arguments) response = consumer.token_request(consumer.http_method, (consumer.access_token_url? ? consumer.access_token_url : consumer.access_token_path), self, options, *arguments) OAuth::AccessToken.from_hash(consumer, response) end protected # construct an authorization url def build_authorize_url(base_url, params) uri = URI.parse(base_url.to_s) # TODO doesn't handle array values correctly uri.query = params.map { |k,v| [k, CGI.escape(v)] * "=" } * "&" uri.to_s end end end oauth-0.4.7/lib/oauth/tokens/consumer_token.rb0000644000004100000410000000172512055513522021450 0ustar www-datawww-datamodule OAuth # Superclass for tokens used by OAuth Clients class ConsumerToken < Token attr_accessor :consumer, :params attr_reader :response def self.from_hash(consumer, hash) token = self.new(consumer, hash[:oauth_token], hash[:oauth_token_secret]) token.params = hash token end def initialize(consumer, token="", secret="") super(token, secret) @consumer = consumer @params = {} end # Make a signed request using given http_method to the path # # @token.request(:get, '/people') # @token.request(:post, '/people', @person.to_xml, { 'Content-Type' => 'application/xml' }) # 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 def sign!(request, options = {}) consumer.sign!(request, self, options) end end end oauth-0.4.7/lib/oauth/signature.rb0000644000004100000410000000301712055513522017107 0ustar www-datawww-datamodule OAuth module Signature # Returns a list of available signature methods def self.available_methods @available_methods ||= {} end # Build a signature from a +request+. # # 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 || ((c = request.options[:consumer]) && c.options[:signature_method]) || "").downcase] raise UnknownSignatureMethod, request.signature_method unless klass klass.new(request, options, &block) end # Sign a +request+ def self.sign(request, options = {}, &block) self.build(request, options, &block).signature end # Verify the signature of +request+ def self.verify(request, options = {}, &block) self.build(request, options, &block).verify end # Create the signature base string for +request+. This string is the normalized parameter information. # # See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1] 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 oauth-0.4.7/lib/oauth/errors.rb0000644000004100000410000000014012055513522016414 0ustar www-datawww-datarequire 'oauth/errors/error' require 'oauth/errors/unauthorized' require 'oauth/errors/problem' oauth-0.4.7/lib/oauth/helper.rb0000644000004100000410000000722412055513522016371 0ustar www-datawww-datarequire 'openssl' require 'base64' module OAuth module Helper extend self # 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) 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 # characters removed. def generate_key(size=32) Base64.encode64(OpenSSL::Random.random_bytes(size)).gsub(/\W/, '') end alias_method :generate_nonce, :generate_key def generate_timestamp #:nodoc: Time.now.to_i.to_s end # Normalize a +Hash+ of parameter values. Parameters are sorted by name, using lexicographical # byte value ordering. If two or more parameters share the same name, they are sorted by their value. # Parameters are concatenated in their sorted order into a single string. For each parameter, the name # is separated from the corresponding value by an "=" character, even if the value is empty. Each # name-value pair is separated by an "&" character. # # 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 # valid hash. Does not validate the keys or values. # # hash = parse_header(headers['Authorization'] || headers['WWW-Authenticate']) # hash['oauth_timestamp'] # #=>"1234567890" # def parse_header(header) # decompose 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 params.map! do |v| # strip and unescape val = unescape(v.strip) # strip quotes val.sub(/^\"(.*)\"$/, '\1') end # convert into a Hash Hash[*params.flatten] end 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 oauth-0.4.7/lib/oauth/server.rb0000644000004100000410000000300012055513522016404 0ustar www-datawww-datarequire 'oauth/helper' require 'oauth/consumer' module OAuth # This is mainly used to create consumer credentials and can pretty much be ignored if you want to create your own class Server include OAuth::Helper attr_accessor :base_url @@server_paths = { :request_token_path => "/oauth/request_token", :authorize_path => "/oauth/authorize", :access_token_path => "/oauth/access_token" } # Create a new server instance def initialize(base_url, paths = {}) @base_url = base_url @paths = @@server_paths.merge(paths) end def generate_credentials [generate_key(16), generate_key] end def generate_consumer_credentials(params = {}) Consumer.new(*generate_credentials) end # mainly for testing purposes def create_consumer creds = generate_credentials Consumer.new(creds[0], creds[1], { :site => base_url, :request_token_path => request_token_path, :authorize_path => authorize_path, :access_token_path => access_token_path }) end def request_token_path @paths[:request_token_path] end def request_token_url base_url + request_token_path end def authorize_path @paths[:authorize_path] end def authorize_url base_url + authorize_path end def access_token_path @paths[:access_token_path] end def access_token_url base_url + access_token_path end end end oauth-0.4.7/lib/oauth/signature/0000755000004100000410000000000012055513522016561 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/signature/sha1.rb0000644000004100000410000000033412055513522017742 0ustar www-datawww-datarequire 'oauth/signature/base' require 'digest/sha1' module OAuth::Signature class SHA1 < Base implements 'sha1' digest_class Digest::SHA1 def signature_base_string secret + super end end end oauth-0.4.7/lib/oauth/signature/base.rb0000644000004100000410000000557112055513522020030 0ustar www-datawww-datarequire 'oauth/signature' require 'oauth/helper' require 'oauth/request_proxy/base' require 'base64' module OAuth::Signature class Base include OAuth::Helper attr_accessor :options attr_reader :token_secret, :consumer_secret, :request 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 @options = options ## consumer secret was determined beforehand @consumer_secret = options[:consumer].secret if options[:consumer] # presence of :consumer_secret option will override any Consumer that's provided @consumer_secret = options[:consumer_secret] if options[:consumer_secret] ## token secret was determined beforehand @token_secret = options[:token].secret if options[:token] # 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 secrets = yield block.arity == 1 ? request : [token, consumer_key, nonce, request.timestamp] if secrets.is_a?(Array) && secrets.size == 2 @token_secret = secrets[0] @consumer_secret = secrets[1] end end end def signature Base64.encode64(digest).chomp.gsub(/\n/,'') end def ==(cmp_signature) Base64.decode64(signature) == Base64.decode64(cmp_signature) end def verify self == self.request.signature end 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 request.token end def consumer_key request.consumer_key end def nonce request.nonce end def secret "#{escape(consumer_secret)}&#{escape(token_secret)}" end def digest self.class.digest_class.digest(signature_base_string) end end end oauth-0.4.7/lib/oauth/signature/plaintext.rb0000644000004100000410000000052312055513522021116 0ustar www-datawww-datarequire 'oauth/signature/base' module OAuth::Signature class PLAINTEXT < Base implements 'plaintext' def signature signature_base_string end def ==(cmp_signature) signature.to_s == cmp_signature.to_s end def signature_base_string secret end def secret super end end end oauth-0.4.7/lib/oauth/signature/md5.rb0000644000004100000410000000033012055513522017567 0ustar www-datawww-datarequire 'oauth/signature/base' require 'digest/md5' module OAuth::Signature class MD5 < Base implements 'md5' digest_class Digest::MD5 def signature_base_string secret + super end end end oauth-0.4.7/lib/oauth/signature/hmac/0000755000004100000410000000000012055513522017471 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/signature/hmac/sha1.rb0000644000004100000410000000026212055513522020652 0ustar www-datawww-datarequire 'oauth/signature/hmac/base' module OAuth::Signature::HMAC class SHA1 < Base implements 'hmac-sha1' digest_klass 'SHA1' hash_class ::Digest::SHA1 end end oauth-0.4.7/lib/oauth/signature/hmac/base.rb0000644000004100000410000000055412055513522020734 0ustar www-datawww-data# -*- 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 Object.module_eval("::Digest::#{self.class.digest_klass}") Digest::HMAC.digest(signature_base_string, secret, self.class.digest_class) end end end oauth-0.4.7/lib/oauth/signature/hmac/sha2.rb0000644000004100000410000000022412055513522020651 0ustar www-datawww-datarequire 'oauth/signature/hmac/base' module OAuth::Signature::HMAC class SHA2 < Base implements 'hmac-sha2' digest_klass 'SHA2' end end oauth-0.4.7/lib/oauth/signature/hmac/md5.rb0000644000004100000410000000022112055513522020476 0ustar www-datawww-datarequire 'oauth/signature/hmac/base' module OAuth::Signature::HMAC class MD5 < Base implements 'hmac-md5' digest_class 'MD5' end end oauth-0.4.7/lib/oauth/signature/hmac/rmd160.rb0000644000004100000410000000023212055513522021024 0ustar www-datawww-datarequire 'oauth/signature/hmac/base' module OAuth::Signature::HMAC class RMD160 < Base implements 'hmac-rmd160' digest_klass 'RMD160' end end oauth-0.4.7/lib/oauth/signature/rsa/0000755000004100000410000000000012055513522017346 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/signature/rsa/sha1.rb0000644000004100000410000000217312055513522020532 0ustar www-datawww-datarequire 'oauth/signature/base' require 'openssl' 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) end def public_key if consumer_secret.is_a?(String) decode_public_key elsif consumer_secret.is_a?(OpenSSL::X509::Certificate) consumer_secret.public_key else consumer_secret end end private def decode_public_key case consumer_secret when /-----BEGIN CERTIFICATE-----/ OpenSSL::X509::Certificate.new( consumer_secret).public_key else OpenSSL::PKey::RSA.new( consumer_secret) end end def digest private_key = OpenSSL::PKey::RSA.new( if options[:private_key_file] IO.read(options[:private_key_file]) else consumer_secret end ) private_key.sign(OpenSSL::Digest::SHA1.new, signature_base_string) end end end oauth-0.4.7/lib/oauth/core_ext.rb0000644000004100000410000000063012055513522016714 0ustar www-datawww-data# 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 oauth-0.4.7/lib/oauth/errors/0000755000004100000410000000000012055513522016074 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/errors/problem.rb0000644000004100000410000000041112055513522020055 0ustar www-datawww-datamodule OAuth class Problem < OAuth::Unauthorized attr_reader :problem, :params def initialize(problem, request = nil, params = {}) super(request) @problem = problem @params = params end def to_s problem end end end oauth-0.4.7/lib/oauth/errors/error.rb0000644000004100000410000000006512055513522017553 0ustar www-datawww-datamodule OAuth class Error < StandardError end end oauth-0.4.7/lib/oauth/errors/unauthorized.rb0000644000004100000410000000033112055513522021137 0ustar www-datawww-datamodule OAuth class Unauthorized < OAuth::Error attr_reader :request def initialize(request = nil) @request = request end def to_s [request.code, request.message] * " " end end end oauth-0.4.7/lib/oauth/oauth.rb0000644000004100000410000000100112055513522016215 0ustar www-datawww-datamodule OAuth # request tokens are passed between the consumer and the provider out of # band (i.e. callbacks cannot be used), per section 6.1.1 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 oauth_body_hash) # reserved character regexp, per section 5.1 RESERVED_CHARACTERS = /[^a-zA-Z0-9\-\.\_\~]/ end oauth-0.4.7/lib/oauth/client/0000755000004100000410000000000012055513522016036 5ustar www-datawww-dataoauth-0.4.7/lib/oauth/client/action_controller_request.rb0000644000004100000410000000360012055513522023652 0ustar www-datawww-datarequire 'oauth/client/helper' if defined? ActionDispatch require 'oauth/request_proxy/rack_request' require 'action_dispatch/testing/test_process' else require 'oauth/request_proxy/action_controller_request' require 'action_controller/test_process' end module ActionController class Base if defined? ActionDispatch def process_with_new_base_test(request, response=nil) request.apply_oauth! if request.respond_to?(:apply_oauth!) super(request, response) end else def process_with_oauth(request, response=nil) request.apply_oauth! if request.respond_to?(:apply_oauth!) process_without_oauth(request, response) end alias_method_chain :process, :oauth end end class TestRequest def self.use_oauth=(bool) @use_oauth = bool end def self.use_oauth? @use_oauth end def configure_oauth(consumer = nil, token = nil, options = {}) @oauth_options = { :consumer => consumer, :token => token, :scheme => 'header', :signature_method => nil, :nonce => nil, :timestamp => nil }.merge(options) end def apply_oauth! return unless ActionController::TestRequest.use_oauth? && @oauth_options @oauth_helper = OAuth::Client::Helper.new(self, @oauth_options.merge(:request_uri => (respond_to?(:fullpath) ? fullpath : request_uri))) @oauth_helper.amend_user_agent_header(env) self.send("set_oauth_#{@oauth_options[:scheme]}") end def set_oauth_header env['Authorization'] = @oauth_helper.header end def set_oauth_parameters @query_parameters = @oauth_helper.parameters_with_oauth @query_parameters.merge!(:oauth_signature => @oauth_helper.signature) end def set_oauth_query_string end end end oauth-0.4.7/lib/oauth/client/net_http.rb0000644000004100000410000001134412055513522020213 0ustar www-datawww-datarequire 'oauth/helper' require 'oauth/client/helper' require 'oauth/request_proxy/net_http' class Net::HTTPGenericRequest include OAuth::Helper attr_reader :oauth_helper # Add the OAuth information to an HTTP request. Depending on the options[:scheme] setting # 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 # * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+, # +signature_method+, +nonce+, +timestamp+) # # This method also modifies the User-Agent 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], # {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 = {}) 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) @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 options[:scheme] 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], # {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 = {}) 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_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 uri.scheme = "http" end 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, 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.stringify_keys(@oauth_helper.parameters_with_oauth)) params_with_sig = @oauth_helper.parameters.merge(:oauth_signature => @oauth_helper.signature) 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 else uri.query = uri.query + "&" + oauth_params_str end @path = uri.to_s @path << "&oauth_signature=#{escape(oauth_helper.signature)}" end end oauth-0.4.7/lib/oauth/client/helper.rb0000644000004100000410000000575512055513522017656 0ustar www-datawww-datarequire 'oauth/client' require 'oauth/consumer' require 'oauth/helper' require 'oauth/token' require 'oauth/signature/hmac/sha1' module OAuth::Client class Helper include OAuth::Helper def initialize(request, options = {}) @request = request @options = options @options[:signature_method] ||= 'HMAC-SHA1' end def options @options end def nonce options[:nonce] ||= generate_key end def timestamp options[:timestamp] ||= generate_timestamp end 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' => (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], :unsigned_parameters => options[:unsigned_parameters] }.merge(extra_options) ) end def signature_base_string(extra_options = {}) OAuth::Signature.signature_base_string(@request, { :uri => options[:request_uri], :consumer => options[:consumer], :token => options[:token], :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}" # 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 end end def header parameters = oauth_parameters parameters.merge!('oauth_signature' => signature(options.merge(:parameters => parameters))) header_params_str = parameters.sort.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ') realm = "realm=\"#{options[:realm]}\", " if options[:realm] "OAuth #{realm}#{header_params_str}" end def parameters OAuth::RequestProxy.proxy(@request).parameters end def parameters_with_oauth oauth_parameters.merge(parameters) end end end oauth-0.4.7/lib/oauth/client/em_http.rb0000644000004100000410000001077312055513522020033 0ustar www-datawww-datarequire 'em-http' require 'oauth/helper' require 'oauth/client/helper' require 'oauth/request_proxy/em_http_request' # Extensions for em-http so that we can use consumer.sign! with an EventMachine::HttpClient # instance. This is purely syntactic sugar. class EventMachine::HttpClient attr_reader :oauth_helper # Add the OAuth information to an HTTP request. Depending on the options[:scheme] setting # 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, ignored in this scenario except for getting host. # * consumer - OAuth::Consumer instance # * token - OAuth::Token instance # * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+, # +signature_method+, +nonce+, +timestamp+) # # This method also modifies the User-Agent 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] def oauth!(http, consumer = nil, token = nil, options = {}) options = { :request_uri => normalized_oauth_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) self.__send__(:"set_oauth_#{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 options[:scheme] 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] def signature_base_string(http, consumer = nil, token = nil, options = {}) options = { :request_uri => normalized_oauth_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 end # This code was lifted from the em-http-request because it was removed from # the gem June 19, 2010 # see: http://github.com/igrigorik/em-http-request/commit/d536fc17d56dbe55c487eab01e2ff9382a62598b def normalize_uri @normalized_uri ||= begin uri = @uri.dup encoded_query = encode_query(@uri, @options[:query]) path, query = encoded_query.split("?", 2) uri.query = query unless encoded_query.empty? uri.path = path uri end end protected def combine_query(path, query, uri_query) combined_query = if query.kind_of?(Hash) query.map { |k, v| encode_param(k, v) }.join('&') else query.to_s end if !uri_query.to_s.empty? combined_query = [combined_query, uri_query].reject {|part| part.empty?}.join("&") end combined_query.to_s.empty? ? path : "#{path}?#{combined_query}" end # Since we expect to get the host etc details from the http instance (...), # we create a fake url here. Surely this is a horrible, horrible idea? def normalized_oauth_uri(http) uri = URI.parse(normalize_uri.path) uri.host = http.address uri.port = http.port if http.respond_to?(:use_ssl?) && http.use_ssl? uri.scheme = "https" else uri.scheme = "http" end uri.to_s end def set_oauth_header headers = (self.options[:head] ||= {}) headers['Authorization'] = @oauth_helper.header end def set_oauth_body raise NotImplementedError, 'please use the set_oauth_header method instead' end def set_oauth_query_string raise NotImplementedError, 'please use the set_oauth_header method instead' end end oauth-0.4.7/lib/oauth/consumer.rb0000644000004100000410000003112212055513522016737 0ustar www-datawww-datarequire 'net/http' require 'net/https' require 'oauth/oauth' require 'oauth/client/net_http' require 'oauth/errors' require 'cgi' module OAuth class Consumer # determine the certificate authority path to verify SSL certs CA_FILES = %w(/etc/ssl/certs/ca-certificates.crt /usr/share/curl/curl-ca-bundle.crt) CA_FILES.each do |ca_file| if File.exists?(ca_file) CA_FILE = ca_file break end end CA_FILE = nil unless defined?(CA_FILE) @@default_options = { # Signature method used by server. Defaults to HMAC-SHA1 :signature_method => 'HMAC-SHA1', # default paths on site. These are the same as the defaults set up by the generators :request_token_path => '/oauth/request_token', :authorize_path => '/oauth/authorize', :access_token_path => '/oauth/access_token', :proxy => nil, # How do we send the oauth values to the server see # http://oauth.net/core/1.0/#consumer_req_param for more info # # Possible values: # # :header - via the Authorize header (Default) ( option 1. in spec) # :body - url form encoded in body of POST request ( option 2. in spec) # :query_string - via the query part of the url ( option 3. in spec) :scheme => :header, # Default http method used for OAuth Token Requests (defaults to :post) :http_method => :post, # Add a custom ca_file for consumer # :ca_file => '/etc/certs.pem' :oauth_version => "1.0" } attr_accessor :options, :key, :secret attr_writer :site, :http # Create a new consumer instance by passing it a configuration hash: # # @consumer = OAuth::Consumer.new(key, secret, { # :site => "http://term.ie", # :scheme => :header, # :http_method => :post, # :request_token_path => "/oauth/example/request_token.php", # :access_token_path => "/oauth/example/access_token.php", # :authorize_path => "/oauth/example/authorize.php" # }) # # Start the process by requesting a token # # @request_token = @consumer.get_request_token # session[:request_token] = @request_token # redirect_to @request_token.authorize_url # # When user returns create an access_token # # @access_token = @request_token.get_access_token # @photos=@access_token.get('/photos.xml') # def initialize(consumer_key, consumer_secret, options = {}) @key = consumer_key @secret = consumer_secret # ensure that keys are symbols @options = @@default_options.merge(options.inject({}) do |opts, (key, value)| opts[key.to_sym] = value opts end) end # The default http method def http_method @http_method ||= @options[:http_method] || :post end # The HTTP object for the site. The HTTP Object is what you get when you do Net::HTTP.new def http @http ||= create_http end # Contains the root URI for this site def uri(custom_uri = nil) if custom_uri @uri = custom_uri @http = create_http # yike, oh well. less intrusive this way else # if no custom passed, we use existing, which, if unset, is set to site uri @uri ||= URI.parse(site) end end 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 # Makes a request to the service for a new OAuth::RequestToken # # @request_token = @consumer.get_request_token # # To include OAuth parameters: # # @request_token = @consumer.get_request_token \ # :oauth_callback => "http://example.com/cb" # # To include application-specific parameters: # # @request_token = @consumer.get_request_token({}, :foo => "bar") # # TODO oauth_callback should be a mandatory parameter 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 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 # Creates, signs and performs an http request. # It's recommended to use the OAuth::Token classes to set this up correctly. # request_options take precedence over consumer-wide options when signing # a request. # arguments are POST and PUT bodies (a Hash, string-encoded parameters, or # absent), followed by additional HTTP headers. # # @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) 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) 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 { |hdr| hdr =~ /^OAuth / }).any? && h.first =~ /oauth_problem/ # puts "Header: #{h.first}" # TODO doesn't handle broken responses from api.login.yahoo.com # remove debug code when done params = OAuth::Helper.parse_header(h.first) # puts "Params: #{params.inspect}" # puts "Body: #{rsp.body}" raise OAuth::Problem.new(params.delete("oauth_problem"), rsp, params) end rsp end # Creates and signs an http request. # It's recommended to use the Token classes to set this up correctly def create_signed_request(http_method, path, token = nil, request_options = {}, *arguments) request = create_http_request(http_method, path, *arguments) sign!(request, token, request_options) request end # 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) 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 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 response.error! end end # Sign the Request object. Use this if you have an externally generated http request object you want to sign. def sign!(request, token = nil, request_options = {}) request.oauth!(http, self, token, options.merge(request_options)) end # Return the signature_base_string def signature_base_string(request, token = nil, request_options = {}) request.signature_base_string(http, self, token, options.merge(request_options)) end 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 def request_token_path @options[:request_token_path] end def authorize_path @options[:authorize_path] end def access_token_path @options[:access_token_path] end # TODO this is ugly, rewrite def request_token_url @options[:request_token_url] || site + request_token_path end def request_token_url? @options.has_key?(:request_token_url) end def authorize_url @options[:authorize_url] || site + authorize_path end def authorize_url? @options.has_key?(:authorize_url) end def access_token_url @options[:access_token_url] || site + access_token_path end def access_token_url? @options.has_key?(:access_token_url) end def proxy @options[:proxy] end 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 proxy_uri = proxy.is_a?(URI) ? proxy : URI.parse(proxy) http_object = Net::HTTP.new(our_uri.host, our_uri.port, proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password) end http_object.use_ssl = (our_uri.scheme == 'https') if @options[:ca_file] || CA_FILE http_object.ca_file = @options[:ca_file] || CA_FILE http_object.verify_mode = OpenSSL::SSL::VERIFY_PEER http_object.verify_depth = 5 else http_object.verify_mode = OpenSSL::SSL::VERIFY_NONE end http_object.read_timeout = http_object.open_timeout = @options[:timeout] || 30 http_object.open_timeout = @options[:open_timeout] if @options[:open_timeout] http_object end # create the http request object for a given http_method and path def create_http_request(http_method, path, *arguments) http_method = http_method.to_sym if [:post, :put].include?(http_method) data = arguments.shift end # if the base site contains a path, add it now uri = URI.parse(site) path = uri.path + path if uri.path && 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 when :put request = Net::HTTP::Put.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :get request = Net::HTTP::Get.new(path,headers) when :delete request = Net::HTTP::Delete.new(path,headers) when :head request = Net::HTTP::Head.new(path,headers) else raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}" end if data.is_a?(Hash) request.body = OAuth::Helper.normalize(data) request.content_type = 'application/x-www-form-urlencoded' elsif data if data.respond_to?(:read) request.body_stream = data if data.respond_to?(:length) request["Content-Length"] = data.length.to_s elsif data.respond_to?(:stat) && data.stat.respond_to?(: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.to_s end end request end def marshal_dump(*args) {:key => @key, :secret => @secret, :options => @options} end def marshal_load(data) initialize(data[:key], data[:secret], data[:options]) end end end oauth-0.4.7/lib/oauth/oauth_test_helper.rb0000644000004100000410000000151712055513522020627 0ustar www-datawww-datarequire 'action_controller' require 'action_controller/test_process' module OAuth module OAuthTestHelper def mock_incoming_request_with_query(request) incoming = ActionController::TestRequest.new(request.to_hash) incoming.request_uri = request.path incoming.host = request.uri.host incoming.env["SERVER_PORT"] = request.uri.port incoming.env['REQUEST_METHOD'] = request.http_method incoming end def mock_incoming_request_with_authorize_header(request) incoming = ActionController::TestRequest.new incoming.request_uri = request.path incoming.host = request.uri.host incoming.env["HTTP_AUTHORIZATION"] = request.to_auth_string incoming.env["SERVER_PORT"] = request.uri.port incoming.env['REQUEST_METHOD'] = request.http_method incoming end end end oauth-0.4.7/lib/oauth/request_proxy.rb0000644000004100000410000000121212055513522020032 0ustar www-datawww-datamodule OAuth module RequestProxy def self.available_proxies #:nodoc: @available_proxies ||= {} end def self.proxy(request, options = {}) return request if request.kind_of?(OAuth::RequestProxy::Base) klass = available_proxies[request.class] # Search for possible superclass matches. if klass.nil? request_parent = available_proxies.keys.find { |rc| request.kind_of?(rc) } klass = available_proxies[request_parent] end raise UnknownRequestType, request.class.to_s unless klass klass.new(request, options) end class UnknownRequestType < Exception; end end end oauth-0.4.7/lib/oauth.rb0000644000004100000410000000047712055513522015115 0ustar www-datawww-data$LOAD_PATH << File.dirname(__FILE__) unless $LOAD_PATH.include?(File.dirname(__FILE__)) module OAuth VERSION = "0.4.7" end require 'oauth/oauth' require 'oauth/core_ext' require 'oauth/client/helper' require 'oauth/signature/hmac/sha1' require 'oauth/signature/rsa/sha1' require 'oauth/request_proxy/mock_request' oauth-0.4.7/Gemfile.lock0000644000004100000410000000157012055513522015117 0ustar www-datawww-dataGEM remote: http://rubygems.org/ specs: actionpack (2.3.14) activesupport (= 2.3.14) rack (~> 1.1.0) activesupport (2.3.14) addressable (2.2.7) crack (0.3.1) curb (0.8.0) em-http-request (0.2.11) addressable (>= 2.0.0) eventmachine (>= 0.12.9) eventmachine (0.12.10) git (1.2.5) jeweler (1.8.3) bundler (~> 1.0) git (>= 1.2.5) rake rdoc json (1.6.6) metaclass (0.0.1) mime-types (1.18) mocha (0.11.1) metaclass (~> 0.0.1) rack (1.1.3) rake (0.9.2.2) rdoc (3.12) json (~> 1.4) typhoeus (0.3.3) mime-types webmock (1.8.6) addressable (>= 2.2.7) crack (>= 0.1.7) PLATFORMS ruby DEPENDENCIES actionpack (~> 2.3.8) curb (>= 0.6.6.0) em-http-request (= 0.2.11) jeweler mocha (>= 0.9.8) rake typhoeus (>= 0.1.13) webmock