diff --git a/lib/restclient/request.rb b/lib/restclient/request.rb index 6841d2e..7ea0d43 100644 --- a/lib/restclient/request.rb +++ b/lib/restclient/request.rb @@ -1,6 +1,7 @@ require 'tempfile' require 'mime/types' require 'cgi' +require 'netrc' module RestClient # This class is used internally by RestClient to send the request, but you can also @@ -116,6 +117,9 @@ module RestClient uri = parse_url(url) @user = CGI.unescape(uri.user) if uri.user @password = CGI.unescape(uri.password) if uri.password + if !@user && !@password + @user, @password = Netrc.read[uri.host] + end uri end diff --git a/rest-client.gemspec b/rest-client.gemspec index 8e1e4cb..67ee18f 100644 --- a/rest-client.gemspec +++ b/rest-client.gemspec @@ -72,5 +72,6 @@ Gem::Specification.new do |s| s.add_dependency(%q, [">= 0.9.1"]) s.add_dependency(%q, [">= 0"]) end + s.add_dependency(%q, [">= 0"]) end diff --git a/spec/request_spec.rb b/spec/request_spec.rb index 89e01f6..ccb8d3c 100644 --- a/spec/request_spec.rb +++ b/spec/request_spec.rb @@ -109,6 +109,24 @@ describe RestClient::Request do @request.make_headers({}).should == { 'Foo' => 'bar', 'Cookie' => 'session_id=1; user_id=someone'} end + it "uses netrc credentials" do + URI.stub!(:parse).and_return(mock('uri', :user => nil, :password => nil, :host => 'example.com')) + File.stub!(:stat).and_return(mock('stat', :mode => 0600)) + IO.stub!(:readlines).and_return(["machine example.com login a password b"]) + @request.parse_url_with_auth('http://example.com/resource') + @request.user.should == 'a' + @request.password.should == 'b' + end + + it "uses credentials in the url in preference to netrc" do + URI.stub!(:parse).and_return(mock('uri', :user => 'joe%20', :password => 'pass1', :host => 'example.com')) + File.stub!(:stat).and_return(mock('stat', :mode => 0600)) + IO.stub!(:readlines).and_return(["machine example.com login a password b"]) + @request.parse_url_with_auth('http://joe%20:pass1@example.com/resource') + @request.user.should == 'joe ' + @request.password.should == 'pass1' + end + it "determines the Net::HTTP class to instantiate by the method name" do @request.net_http_request_class(:put).should == Net::HTTP::Put end