save cookie from meta tag

master
Kanezoh 2021-06-15 07:13:29 +09:00
parent 378891eda7
commit 0df9f07aef
2 changed files with 39 additions and 13 deletions

View File

@ -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
<html>
<head>
<title>page_title</title>
<meta http-equiv='Set-Cookie' content='id=123;SameSite=None;Secure'>
</head>
<body>
</body>
</html>
BODY
)
WebMock.stub(:get, "html_example.com").to_return(body:
<<-BODY
<html>
<meta>
<head>
<title>page_title</title>
</head>
@ -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")

View File

@ -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