From 0df9f07aef325dffe648726093eeddb2f8b91c62 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Tue, 15 Jun 2021 07:13:29 +0900 Subject: [PATCH] save cookie from meta tag --- spec/agent_spec.cr | 22 ++++++++++++++++++++-- src/mechanize/http/agent.cr | 30 +++++++++++++++++++----------- 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/spec/agent_spec.cr b/spec/agent_spec.cr index dc46cee..792f2c2 100644 --- a/spec/agent_spec.cr +++ b/spec/agent_spec.cr @@ -3,10 +3,21 @@ WebMock.stub(:get, "example.com/") WebMock.stub(:get, "another_domain.com/") WebMock.stub(:get, "example.com/cookies1").to_return(headers: {"Set-Cookie" => "id=123"}) WebMock.stub(:get, "example.com/cookies2").to_return(headers: {"Set-Cookie" => "name=kanezoh"}) -WebMock.stub(:get, "html_example.com").to_return(body: +WebMock.stub(:get, "example.com/meta_cookie").to_return(body: +<<-BODY + + + page_title + + + + + +BODY +) +WebMock.stub(:get, "html_example.com").to_return(body: <<-BODY - page_title @@ -55,6 +66,13 @@ describe "Mechanize Agent test" do agent.request_headers["Cookie"].should eq "id=123; name=kanezoh" end + it "get cookie from meta head" do + agent = Mechanize.new + agent.get("http://example.com/meta_cookie") + agent.get("http://example.com/") + agent.request_headers["Cookie"].should eq "id=123" + end + it "don't send cookies to another domain" do agent = Mechanize.new agent.get("http://example.com/cookies1") diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index a007c33..7931a0e 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -70,21 +70,19 @@ module MechanizeCr end private def add_response_cookies(response, uri, page) - #if page.body =~ /Set-Cookie/ - # page.css("//head/meta[@http-equiv=\"Set-Cookie\"]").each do |meta| - # save_cookies(uri, meta["content"]) - # end - #end + if page.body =~ /Set-Cookie/ + page.css("head meta[http-equiv=\"Set-Cookie\"]").each do |meta| + cookie = meta["content"].split(";")[0] + key,value = cookie.split("=") + cookie = ::HTTP::Cookie.new(name: key, value: value) + save_cookies(uri, [cookie]) + end + end header_cookies = response.try &.cookies if (header_cookies.nil? || header_cookies.try &.empty?) return else - if cookies.fetch(uri.host.to_s, ::HTTP::Cookies.new).empty? - cookies[uri.host.to_s] = ::HTTP::Cookies.new - end - header_cookies.each do |cookie| - cookies[uri.host.to_s] << cookie - end + save_cookies(uri, header_cookies) end end @@ -107,6 +105,16 @@ module MechanizeCr private def reset_request_header_cookies request_headers.delete("Cookie") end + + private def save_cookies(uri, header_cookies) + host = uri.host.to_s + if cookies.fetch(host, ::HTTP::Cookies.new).empty? + cookies[host] = ::HTTP::Cookies.new + end + header_cookies.each do |cookie| + cookies[host] << cookie + end + end end end end