Skip to content

Commit

Permalink
Add cookie jar for handling HTTP redirection.
Browse files Browse the repository at this point in the history
Add new cookie_jar method to responses, and reimplement cookies using
it. Also dup args when generating redirect options rather than mutating
the args on the response object.
  • Loading branch information
ab committed Mar 22, 2015
1 parent 37d92c0 commit 12e9231
Showing 1 changed file with 35 additions and 12 deletions.
47 changes: 35 additions & 12 deletions lib/restclient/abstract_response.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'cgi'
require 'http-cookie'

module RestClient

Expand All @@ -24,9 +25,28 @@ def raw_headers

# Hash of cookies extracted from response headers
def cookies
@cookies ||= (self.headers[:set_cookie] || {}).inject({}) do |out, cookie_content|
out.merge parse_cookie(cookie_content)
hash = {}

cookie_jar.cookies.each do |out, cookie|
hash[cookie.name] = cookie.value
end

hash
end

# Cookie jar extracted from response headers.
#
# @return [HTTP::CookieJar]
#
def cookie_jar
return @cookie_jar if @cookie_jar

jar = HTTP::CookieJar.new
headers.fetch(:set_cookie, []).each do |cookie|
jar.parse(cookie, @args.fetch(:url))
end

@cookie_jar = jar
end

# Return the default behavior corresponding to the response code:
Expand Down Expand Up @@ -61,25 +81,28 @@ def description

# Follow a redirection
def follow_redirection request = nil, result = nil, & block
new_args = @args.dup

url = headers[:location]
if url !~ /^http/
url = URI.parse(args[:url]).merge(url).to_s
end
args[:url] = url
new_args[:url] = url
if request
if request.max_redirects == 0
raise MaxRedirectsReached
end
args[:password] = request.password
args[:user] = request.user
args[:headers] = request.headers
args[:max_redirects] = request.max_redirects - 1
# pass any cookie set in the result
if result && result['set-cookie']
args[:headers][:cookies] = (args[:headers][:cookies] || {}).merge(parse_cookie(result['set-cookie']))
end
new_args[:password] = request.password
new_args[:user] = request.user
new_args[:headers] = request.headers
new_args[:max_redirects] = request.max_redirects - 1

# TODO: figure out what to do with original :cookie, :cookies values
new_args[:headers]['Cookie'] = HTTP::Cookie.cookie_value(
cookie_jar.cookies(new_args.fetch(:url)))
end
Request.execute args, &block

Request.execute(new_args, &block)
end

def self.beautify_headers(headers)
Expand Down

0 comments on commit 12e9231

Please sign in to comment.